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

import argparse
import json
import os
import urllib.error
import urllib.request
from pathlib import Path
from typing import Any

ROOT = Path(__file__).resolve().parents[1]
DEFAULT_BASE_URL = "https://gitea.taxbaik.com"
DEFAULT_OWNER = "kjh2064"
DEFAULT_REPO = "QuantEngineByItz"


def _get_token(cli_token: str = "") -> str:
    """토큰 우선순위: CLI → GITEA_TOKEN_BAIK → GITEA_TOKEN_TAXBAIK → GITEA_TOKEN → GITEA_TOKEN_HOME"""
    if cli_token and cli_token.strip():
        return cli_token.strip()
    for env_key in ("GITEA_TOKEN_BAIK", "GITEA_TOKEN_TAXBAIK", "GITEA_TOKEN", "GITEA_TOKEN_HOME"):
        val = os.environ.get(env_key, "").strip()
        if val:
            return val
    return ""


def _request_json(url: str, token: str = "", method: str = "GET") -> tuple[int, str, Any]:
    headers = {
        "Accept": "application/json",
        "User-Agent": "QuantEngine-Harness/1.0",
    }
    if token:
        headers["Authorization"] = f"token {token}"

    req = urllib.request.Request(url, headers=headers, method=method)
    try:
        with urllib.request.urlopen(req, timeout=30) as resp:
            raw = resp.read().decode("utf-8", errors="replace")
            payload = json.loads(raw) if raw else None
            return resp.status, resp.reason, payload
    except urllib.error.HTTPError as exc:
        raw = exc.read().decode("utf-8", errors="replace")
        try:
            payload = json.loads(raw) if raw else None
        except Exception:
            payload = raw
        return exc.code, exc.reason or "", payload


def main() -> int:
    ap = argparse.ArgumentParser(description="Gitea Actions API Inspector Harness Tool")
    ap.add_argument("--base-url", default=DEFAULT_BASE_URL)
    ap.add_argument("--owner", default=DEFAULT_OWNER)
    ap.add_argument("--repo", default=DEFAULT_REPO)
    ap.add_argument("--run-id", type=int, default=2545)
    ap.add_argument("--token", default=None, help="Optional Gitea API Token")
    args = ap.parse_args()

    token = args.token or _get_token()
    repo_url = f"{args.base_url.rstrip('/')}/api/v1/repos/{args.owner}/{args.repo}"

    # 1. Fetch Repository Info
    status, reason, repo_info = _request_json(repo_url, token=token)

    # 2. Fetch Actions Runs List
    runs_url = f"{repo_url}/actions/runs"
    status_runs, reason_runs, runs_payload = _request_json(runs_url, token=token)

    target_run = None
    if isinstance(runs_payload, dict):
        workflow_runs = runs_payload.get("workflow_runs") or []
        for r in workflow_runs:
            if r.get("id") == args.run_id or r.get("run_number") == args.run_id:
                target_run = r
                break
        if not target_run and workflow_runs:
            target_run = workflow_runs[0] # Fallback to latest

    result = {
        "formula_id": "GITEA_ACTIONS_RUN_INSPECTOR_V1",
        "gate": "PASS" if status == 200 and status_runs == 200 else "FAIL",
        "repository": f"{args.owner}/{args.repo}",
        "target_run_id": args.run_id,
        "token_provided": bool(token),
        "run_details": target_run or runs_payload,
        "meta": {
            "api_status": status,
            "runs_status": status_runs,
            "runs_reason": reason_runs
        }
    }

    out = ROOT / "Temp" / "gitea_actions_run_2545_v1.json"
    out.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps(result, ensure_ascii=False, indent=2))
    return 0 if (status == 200 and status_runs == 200) else 1


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