#!/usr/bin/env python3
"""
CI Report Generator
Reads CI results from JSON (ci.sh output) and generates a human-readable report.
"""

import argparse
import json
import os
import subprocess
import sys
from datetime import datetime
from pathlib import Path

WORKSPACE = Path(os.environ.get("WORKSPACE_ROOT", str(Path(__file__).resolve().parent.parent)))
CI_LATEST = WORKSPACE / "memory/logs/ci-latest.json"
CI_HISTORY = WORKSPACE / "memory/logs/ci-history.jsonl"

STAGE_ORDER = [
    "syntax_check",
    "pytest",
    "coverage",
    "pip_audit",
    "run_tests",
    "health_check",
]


def read_ci_result(file_path):
    """Read CI result from JSON file."""
    try:
        with open(file_path, "r", encoding="utf-8") as f:
            data = json.load(f)
        return data
    except FileNotFoundError:
        print(f"Error: CI result file not found: {file_path}", file=sys.stderr)
        sys.exit(1)
    except json.JSONDecodeError as e:
        print(f"Error: Invalid JSON in {file_path}: {e}", file=sys.stderr)
        sys.exit(1)


def append_to_history(result):
    """Append result to CI history file (JSONL format)."""
    try:
        CI_HISTORY.parent.mkdir(parents=True, exist_ok=True)
        with open(CI_HISTORY, "a", encoding="utf-8") as f:
            f.write(json.dumps(result, ensure_ascii=False) + "\n")
    except Exception as e:
        print(f"Warning: Could not append to history: {e}", file=sys.stderr)


def format_timestamp(timestamp_str):
    """Format timestamp for display."""
    try:
        dt = datetime.fromisoformat(timestamp_str.replace("Z", "+00:00"))
        return dt.strftime("%Y-%m-%d %H:%M:%S")
    except Exception:
        return timestamp_str


def status_label(status):
    """Return uppercase status label."""
    s = (status or "unknown").upper()
    if s in ("PASS", "WARN", "FAIL", "SKIP"):
        return f"[{s}]"
    return f"[{s}]"


def print_report(result):
    """Print formatted CI report to console."""
    timestamp = result.get("timestamp", datetime.now().isoformat())
    formatted_time = format_timestamp(timestamp)
    stages = result.get("stages", {})
    duration = result.get("duration_seconds", "unknown")
    verdict = result.get("verdict", "UNKNOWN")

    print("═" * 37)
    print(f"CI REPORT — {formatted_time}")
    print("═" * 37)

    for stage_name in STAGE_ORDER:
        stage = stages.get(stage_name, {})
        status = (stage.get("status") or "unknown").upper()
        detail = stage.get("detail", "")
        label = status_label(status)
        if detail:
            print(f"{label} {stage_name:<15} — {detail}")
        else:
            print(f"{label} {stage_name}")

    print()
    print(f"Verdict: {verdict} | Duration: {duration}s")
    print("═" * 37)

    return verdict


def send_notification_on_fail(verdict):
    """Send notification via cokacdir if verdict is FAIL."""
    if verdict != "FAIL":
        return

    cmd = [
        "cokacdir",
        "--cron",
        "CI 실패 감지. /home/jay/workspace/memory/logs/ci-latest.json 결과 확인 필요.",
        "--at",
        "10s",
        "--chat",
        os.environ.get("COKACDIR_CHAT_ID", "6937032012"),
        "--key",
        os.environ.get("COKACDIR_KEY_ANU", "c119085addb0f8b7"),
        "--once",
    ]

    try:
        subprocess.run(cmd, check=False)
    except Exception as e:
        print(f"Warning: Could not send notification: {e}", file=sys.stderr)


def main():
    parser = argparse.ArgumentParser(
        description="Generate CI report from JSON result (ci.sh output)",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="Examples:\n" "  python3 ci-report.py\n" "  python3 ci-report.py --file /path/to/result.json",
    )

    parser.add_argument(
        "--file",
        type=str,
        default=None,
        help="Path to CI result JSON file (default: memory/logs/ci-latest.json)",
    )

    args = parser.parse_args()

    ci_file = Path(args.file) if args.file else CI_LATEST

    result = read_ci_result(ci_file)
    append_to_history(result)
    verdict = print_report(result)
    send_notification_on_fail(verdict)

    sys.exit(0 if verdict in ("PASS", "WARN") else 1)


if __name__ == "__main__":
    main()
