#!/usr/bin/env python3
"""Production helper: Point 2 — design reject → clarify → redesign.

Usage:
  python3 scripts/test_point2_reject_loop.py create
  python3 scripts/test_point2_reject_loop.py status AN-XX
  python3 scripts/test_point2_reject_loop.py comment AN-XX 'reject — use Contact instead of Account'
  python3 scripts/test_point2_reject_loop.py comment AN-XX 'Put Service_Level__c on Contact, not Account.'
"""

from __future__ import annotations

import base64
import json
import sys
import urllib.request
from pathlib import Path


def load_env() -> dict[str, str]:
    env: dict[str, str] = {}
    for line in Path(__file__).resolve().parents[1].joinpath(".env").read_text().splitlines():
        line = line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        k, v = line.split("=", 1)
        env[k] = v.strip().strip('"').strip("'")
    return env


def jira(env: dict[str, str], method: str, path: str, payload=None):
    auth = base64.b64encode(f"{env['JIRA_EMAIL']}:{env['JIRA_API_TOKEN']}".encode()).decode()
    data = None if payload is None else json.dumps(payload).encode()
    req = urllib.request.Request(
        f"{env['JIRA_BASE_URL'].rstrip('/')}{path}",
        data=data,
        headers={
            "Authorization": f"Basic {auth}",
            "Content-Type": "application/json",
            "Accept": "application/json",
        },
        method=method,
    )
    with urllib.request.urlopen(req, timeout=45) as resp:
        raw = resp.read()
        return json.loads(raw) if raw else {}


def adf_text(node) -> str:
    if node is None:
        return ""
    if isinstance(node, str):
        return node
    if isinstance(node, dict):
        if node.get("type") == "text":
            return node.get("text") or ""
        return "".join(adf_text(c) for c in node.get("content") or [])
    if isinstance(node, list):
        return "".join(adf_text(c) for c in node)
    return ""


def cmd_create(env: dict[str, str]) -> None:
    body = {
        "fields": {
            "project": {"key": "AN"},
            "summary": "[Agent Nova test] Point2 — Reject clarify redesign — Service Level on Account",
            "description": {
                "type": "doc",
                "version": 1,
                "content": [
                    {
                        "type": "paragraph",
                        "content": [
                            {
                                "type": "text",
                                "text": (
                                    "Add Service_Level__c picklist on Account "
                                    "(Gold, Silver, Bronze) with default Silver. "
                                    "For testing reject → clarification → redesign."
                                ),
                            }
                        ],
                    }
                ],
            },
            "issuetype": {"name": "Story"},
            "labels": ["agent-nova"],
        }
    }
    created = jira(env, "POST", "/rest/api/3/issue", body)
    key = created["key"]
    print(key)
    print(f"https://agentnovatech.atlassian.net/browse/{key}")
    print()
    print("Next:")
    print(f"  1. Wait until Agent Nova posts a design-review comment on {key}")
    print(f"  2. python3 scripts/test_point2_reject_loop.py comment {key} 'reject — use Contact instead of Account'")
    print(f"  3. Expect a clarification ask (run should NOT fail)")
    print(f"  4. python3 scripts/test_point2_reject_loop.py comment {key} 'Put Service_Level__c on Contact, not Account.'")
    print(f"  5. Expect a NEW design + approve/reject ask again")
    print(f"  6. python3 scripts/test_point2_reject_loop.py status {key}")


def cmd_status(env: dict[str, str], key: str) -> None:
    issue = jira(env, "GET", f"/rest/api/3/issue/{key}?fields=summary,status,labels,comment")
    fields = issue["fields"]
    print(f"{key}  status={fields['status']['name']}  labels={fields.get('labels')}")
    print(f"summary: {fields['summary']}")
    comments = fields.get("comment", {}).get("comments", [])
    print(f"comments: {len(comments)}")
    for c in comments[-8:]:
        author = (c.get("author") or {}).get("displayName", "?")
        text = adf_text(c.get("body")).strip().replace("\n", " | ")
        print(f"  - [{author}] {text[:240]}")


def cmd_comment(env: dict[str, str], key: str, text: str) -> None:
    payload = {
        "body": {
            "type": "doc",
            "version": 1,
            "content": [
                {"type": "paragraph", "content": [{"type": "text", "text": text}]}
            ],
        }
    }
    jira(env, "POST", f"/rest/api/3/issue/{key}/comment", payload)
    print(f"Commented on {key}: {text}")
    print(f"Check: python3 scripts/test_point2_reject_loop.py status {key}")


def main() -> None:
    if len(sys.argv) < 2:
        print(__doc__)
        sys.exit(1)
    env = load_env()
    cmd = sys.argv[1]
    if cmd == "create":
        cmd_create(env)
    elif cmd == "status" and len(sys.argv) >= 3:
        cmd_status(env, sys.argv[2])
    elif cmd == "comment" and len(sys.argv) >= 4:
        cmd_comment(env, sys.argv[2], " ".join(sys.argv[3:]))
    else:
        print(__doc__)
        sys.exit(1)


if __name__ == "__main__":
    main()
