#!/usr/bin/env python3
"""looper-dashboard CLI entrypoint.

Usage:
    looper-dashboard --suite karate            --config flows.yml --scm-url <url>
    looper-dashboard --suite playwright        --config flows.yml --scm-url <url>
    looper-dashboard --suite playwright-monocart --config flows.yml

    looper-dashboard --init karate             # scaffold a starter daily_flows.yml
"""
import argparse
import os
import sys
from datetime import datetime
from pathlib import Path


# ---------------------------------------------------------------------------
# Starter daily_flows.yml templates
# ---------------------------------------------------------------------------

_STARTERS: dict[str, str] = {
    "karate": """\
# Daily Karate Dashboard — flow configuration
# https://github.com/your-org/looper-dashboard

# SCM URL of the repository being monitored
scm_url: https://gecgithub01.walmart.com/YOUR-ORG/YOUR-REPO.git

jobs:

  # Replace with your LooperPro job names and flow names.
  # Discover job names: looper-dashboard --list-jobs --scm-url <url>
  YOUR-ORG/YOUR-REPO:
    - my-flow-dev
    - my-flow-stage
    - my-flow-prod
""",
    "playwright": """\
# Daily Playwright Dashboard — flow configuration
# https://github.com/your-org/looper-dashboard

scm_url: https://gecgithub01.walmart.com/YOUR-ORG/YOUR-REPO.git

jobs:

  YOUR-ORG/YOUR-REPO-tests:
    - e2e-dev
    - e2e-stage
""",
    "playwright-monocart": """\
# Daily Monocart Dashboard — flow configuration
# https://github.com/your-org/looper-dashboard
#
# WPA-style repos that are not discoverable via SCM URL require explicit job_ids.
# Find them in the LooperPro UI or via the mcp-cli tool.

scm_url: https://gecgithub01.walmart.com/YOUR-ORG/YOUR-REPO.git

# Explicit job IDs (required when list_ci_jobs can't find jobs by scm_url)
job_ids:
  wpa-my-job-name: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"

jobs:

  wpa-my-job-name:
    - my-flow
""",
}

_DEFAULT_OUTPUTS: dict[str, str] = {
    "karate":              "karate-daily-dashboard.html",
    "playwright":          "playwright-daily-dashboard.html",
    "playwright-monocart": "wpa-self-service-daily-dashboard.html",
}

_DEFAULT_FAILURES: dict[str, str] = {
    "karate":              "karate-failures.json",
    "playwright":          "playwright-failures.json",
    "playwright-monocart": "wpa-self-service-failures.json",
}

_DEFAULT_ANALYSIS: dict[str, str] = {
    "karate":              "karate-ai-analysis.json",
    "playwright":          "playwright-ai-analysis.json",
    "playwright-monocart": "wpa-self-service-ai-analysis.json",
}

_DEFAULT_DAYS: dict[str, int] = {
    "karate":              14,
    "playwright":          14,
    "playwright-monocart": 30,
}

SUITE_CHOICES = ["karate", "playwright", "playwright-monocart"]


# ---------------------------------------------------------------------------
# main
# ---------------------------------------------------------------------------

def main() -> None:
    parser = argparse.ArgumentParser(
        prog="looper-dashboard",
        description="Generate a daily CI dashboard for any QE repo on LooperPro.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  looper-dashboard --suite karate --config daily_flows.yml --scm-url https://gecgithub01.walmart.com/my-org/my-repo.git --open
  looper-dashboard --suite playwright --config daily_flows.yml --open
  looper-dashboard --suite playwright-monocart --config daily_flows.yml --no-ai
  looper-dashboard --init karate
""",
    )

    parser.add_argument(
        "--suite", choices=SUITE_CHOICES,
        metavar="SUITE",
        help=f"Test suite type: {', '.join(SUITE_CHOICES)}",
    )
    parser.add_argument(
        "--config",
        help="Path to daily_flows.yml (required unless --init is used)",
    )
    parser.add_argument(
        "--scm-url",
        default=None,
        help="Override the scm_url from daily_flows.yml",
    )
    parser.add_argument(
        "--output",
        default=None,
        help="Output HTML file path (default depends on suite)",
    )
    parser.add_argument(
        "--days", type=int, default=None,
        help="Days of build history to fetch (default: 14 for karate/playwright, 30 for monocart)",
    )
    parser.add_argument(
        "--open", dest="auto_open", action="store_true",
        help="Auto-open the dashboard in the browser when done",
    )
    parser.add_argument(
        "--no-ai", action="store_true",
        help="Skip the AI analysis step",
    )
    parser.add_argument(
        "--no-details", action="store_true",
        help="Skip fetching test summary details (faster, status-only)",
    )
    parser.add_argument(
        "--save-failures",
        default=None,
        help="Path to save failures JSON (default depends on suite)",
    )
    parser.add_argument(
        "--analysis-json",
        default=None,
        help="Path to pre-computed AI analysis JSON (skips live AI step)",
    )
    parser.add_argument(
        "--init",
        metavar="SUITE",
        choices=SUITE_CHOICES,
        help="Scaffold a starter daily_flows.yml for the given suite type and exit",
    )

    args = parser.parse_args()

    # --init: scaffold starter config and exit
    if args.init:
        _do_init(args.init)
        return

    # Validate required args for normal run
    if not args.suite:
        parser.error("--suite is required (or use --init to scaffold a config)")
    if not args.config:
        parser.error("--config is required")
    if not Path(args.config).exists():
        print(f"Error: config file not found: {args.config}", file=sys.stderr)
        sys.exit(1)

    suite = args.suite
    config = args.config
    output = args.output or _DEFAULT_OUTPUTS[suite]
    save_failures = args.save_failures or _DEFAULT_FAILURES[suite]
    analysis_json = args.analysis_json or _DEFAULT_ANALYSIS[suite]
    days = args.days or _DEFAULT_DAYS[suite]

    print(f"\nLooper Dashboard — {suite}", flush=True)
    print(f"   {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", flush=True)

    from .orchestrator import (
        step_auth_refresh,
        step_generate_dashboard,
        step_ai_analysis,
        print_summary,
    )

    results: dict[str, bool] = {}

    # Step 1: Auth
    auth_ok = step_auth_refresh()
    results["Auth refresh"] = auth_ok
    if not auth_ok:
        print("\nAuth failed. Please run: mcp-cli auth login", flush=True)
        sys.exit(1)

    # Step 2: Dashboard generation
    dash_ok = step_generate_dashboard(
        suite=suite,
        config=config,
        output=output,
        save_failures=save_failures,
        scm_url=args.scm_url,
        no_details=args.no_details,
        auto_open=args.auto_open and args.no_ai,
        days=days,
    )
    results["Dashboard generation"] = dash_ok
    if not dash_ok:
        print_summary(results, output)
        sys.exit(1)

    # Step 3: AI (optional, or pre-computed)
    if args.analysis_json:
        # Pre-computed analysis provided — skip live AI, just regenerate dashboard
        print(f"\nUsing pre-computed analysis from {args.analysis_json}", flush=True)
        ai_ok = step_ai_analysis(
            suite=suite,
            config=config,
            output=output,
            save_failures=save_failures,
            analysis_json=args.analysis_json,
            scm_url=args.scm_url,
        )
        results["AI analysis (pre-computed)"] = ai_ok
    elif not args.no_ai:
        ai_ok = step_ai_analysis(
            suite=suite,
            config=config,
            output=output,
            save_failures=save_failures,
            analysis_json=analysis_json,
            scm_url=args.scm_url,
        )
        results["AI analysis"] = ai_ok
    else:
        print("\nSkipping AI analysis (--no-ai)", flush=True)

    if args.auto_open and Path(output).exists():
        import platform
        if platform.system() == "Darwin":
            os.system(f"open '{output}'")
        elif platform.system() == "Windows":
            os.startfile(output)  # noqa: S606
        else:
            os.system(f"xdg-open '{output}'")

    print_summary(results, output)


# ---------------------------------------------------------------------------
# --init helper
# ---------------------------------------------------------------------------

def _do_init(suite: str) -> None:
    target = Path("daily_flows.yml")
    if target.exists():
        print(f"daily_flows.yml already exists. Remove it first to reinitialise.", file=sys.stderr)
        sys.exit(1)

    template = _STARTERS[suite]
    target.write_text(template)
    print(f"Created daily_flows.yml for suite '{suite}'.")
    print("Edit it to add your job names and flow names, then run:")
    print(f"  looper-dashboard --suite {suite} --config daily_flows.yml --open")


if __name__ == "__main__":
    main()
