#!/usr/bin/env python3
from __future__ import annotations

import argparse
import html
import json
from pathlib import Path


def build_mermaid(plan: dict) -> str:
    steps = plan.get("steps", [])
    lines = ["graph TD"]
    for step in steps:
        step_id = str(step.get("step_id", "unknown"))
        action = str(step.get("action", ""))
        lines.append(f'  {step_id}["{step_id} | {action}"]')
    for step in steps:
        step_id = str(step.get("step_id", "unknown"))
        for dep in step.get("dependencies", []) or []:
            lines.append(f"  {dep} --> {step_id}")
    return "\n".join(lines)


def render_html(plan: dict, mermaid_graph: str, title: str) -> str:
    pretty = json.dumps(plan, indent=2, ensure_ascii=False)
    return f"""<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>{html.escape(title)}</title>
  <style>
    :root {{
      --bg: #0c1117;
      --panel: #161d26;
      --text: #e6edf3;
      --muted: #9fb0c0;
      --accent: #24c8db;
      --border: #2a3644;
    }}
    html, body {{
      margin: 0; padding: 0; background: var(--bg); color: var(--text);
      font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;
    }}
    .wrap {{
      display: grid;
      grid-template-columns: 1.2fr 1fr;
      gap: 12px;
      padding: 12px;
      min-height: 100vh;
      box-sizing: border-box;
    }}
    .panel {{
      border: 1px solid var(--border);
      border-radius: 10px;
      background: linear-gradient(180deg, #18212b 0%, var(--panel) 100%);
      overflow: auto;
    }}
    .hdr {{
      padding: 10px 12px;
      border-bottom: 1px solid var(--border);
      color: var(--muted);
      font-size: 12px;
      letter-spacing: 0.04em;
      text-transform: uppercase;
    }}
    .body {{
      padding: 12px;
    }}
    pre {{
      margin: 0;
      white-space: pre-wrap;
      word-break: break-word;
      color: var(--text);
      font-size: 12px;
      line-height: 1.35;
    }}
    .hint {{
      margin-top: 8px;
      color: var(--accent);
      font-size: 11px;
    }}
    @media (max-width: 960px) {{
      .wrap {{ grid-template-columns: 1fr; }}
    }}
  </style>
</head>
<body>
  <div class="wrap">
    <section class="panel">
      <div class="hdr">DAG</div>
      <div class="body">
        <pre class="mermaid">{html.escape(mermaid_graph)}</pre>
        <div class="hint">Rendered with Mermaid (like dashboard DAG view).</div>
      </div>
    </section>
    <section class="panel">
      <div class="hdr">Plan JSON</div>
      <div class="body">
        <pre>{html.escape(pretty)}</pre>
      </div>
    </section>
  </div>
  <script type="module">
    import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';
    mermaid.initialize({{ startOnLoad: true, theme: 'dark' }});
  </script>
</body>
</html>
"""


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Render dashboard-style DAG + JSON HTML view.")
    parser.add_argument("plan_json", help="Path to plan JSON file")
    parser.add_argument("--out", help="Output HTML path (default: alongside input)")
    parser.add_argument("--title", default="Orchestrator Plan View")
    return parser.parse_args()


def main() -> int:
    args = parse_args()
    plan_path = Path(args.plan_json)
    plan = json.loads(plan_path.read_text(encoding="utf-8"))
    mermaid_graph = build_mermaid(plan)

    if args.out:
        out_path = Path(args.out)
    else:
        out_path = plan_path.with_suffix(".dashboard.html")

    out_path.write_text(render_html(plan, mermaid_graph, args.title), encoding="utf-8")
    print(out_path)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
