"""
seed_sprint8.py — Załaduj tickety Sprint 8 do platformy proxym.

Uruchom: python scripts/seed_sprint8.py
Lub:     python scripts/seed_sprint8.py --base http://localhost:4000
"""
import argparse
import sys
import httpx

BASE = "http://localhost:4000"
KEY = "sk-proxym-changeme"
HEADERS = {"X-Api-Key": KEY, "Content-Type": "application/json"}


SPRINT = {
    "name": "Sprint 8 — Multi-tool autonomy",
    "goal": (
        "Wyczyścić metryki, rozbić god-modules, dodać listowanie projektów, "
        "smoke testy, integracje narzędzi (aider, claude-code)"
    ),
}


TICKETS = [
    # P0 — Critical
    {
        "title": "Dodaj .toonignore (htmlcov/, services/, *.min.js)",
        "description": (
            "Każda analiza code2llm generuje 6 fałszywych alarmów z htmlcov/. "
            "Dodaj plik .toonignore z wykluczeniami:\n"
            "htmlcov/\n*.min.js\nproject/examples/\nservices/vscode/"
        ),
        "type": "fix",
        "priority": "critical",
        "tags": ["metrics", "code2llm"],
        "tool": "aider",
    },
    {
        "title": "Rozbij dashboard/__init__.py (660L god-module)",
        "description": (
            "God-module z 10 klasami i 39 metodami. Podziel na:\n"
            "  _accounts.py — CRUD kont\n"
            "  _vms.py — CRUD VM-ów\n"
            "  _costs.py — cost endpoints\n"
            "  _tickets_api.py — tickets/sprints REST\n"
            "  _system.py — system status, providers, logs"
        ),
        "type": "refactoring",
        "priority": "critical",
        "tags": ["architecture", "backend", "god-module"],
        "tool": "claude-code",
    },

    # P1 — High
    {
        "title": "Dodaj GET /dashboard/projects — lista projektów z folderu",
        "description": (
            "Dashboard nie wyświetla listy projektów z VSCODE_PROJECT_PATH.\n"
            "Dodaj endpoint skanujący folder i zwracający:\n"
            "  - name, path, has_git, has_pyproject, has_package_json\n"
            "Dodaj UI komponent w dashboardzie."
        ),
        "type": "feature",
        "priority": "high",
        "tags": ["backend", "api", "dashboard"],
        "tool": "vscode",
    },
    {
        "title": "Refaktor list_tickets (CC=17 → ≤10)",
        "description": (
            "Wydziel filtrowanie do _filter_tickets() i _sort_tickets()."
        ),
        "type": "refactoring",
        "priority": "high",
        "tags": ["backend", "complexity"],
        "tool": "aider",
    },
    {
        "title": "Refaktor chat_completions (CC=17 → ≤10)",
        "description": (
            "Wydziel logikę fallbacków do _try_providers() "
            "i error handling do _handle_provider_error()."
        ),
        "type": "refactoring",
        "priority": "high",
        "tags": ["backend", "complexity", "core"],
        "tool": "aider",
    },
    {
        "title": "Dodaj test_tool_health.py — smoke testy narzędzi",
        "description": (
            "Comprehensive smoke test sprawdzający:\n"
            "  - Docker, git, ruff, code2llm available\n"
            "  - Proxy health, models, budget, dashboard\n"
            "  - VS Code Web health\n"
            "  - Provider connectivity\n"
            "  - Chat completion e2e\n"
            "  - Ticket CRUD\n"
            "  - Project listing"
        ),
        "type": "test",
        "priority": "high",
        "tags": ["testing", "smoke", "ci"],
        "tool": "claude-code",
    },
    {
        "title": "Dodaj make test-smoke / health-check targets",
        "description": (
            "Rozszerz Makefile o:\n"
            "  make test-smoke — pytest test_tool_health.py\n"
            "  make health-check — curl-based quick check\n"
            "  make test-tickets — pytest test_tickets*.py\n"
            "  make test-all — pełne testy"
        ),
        "type": "feature",
        "priority": "high",
        "tags": ["devops", "makefile", "ci"],
        "tool": "vscode",
    },

    # P2 — Medium
    {
        "title": "Usuń duplikat VoiceChat z TODO/ (CC=68)",
        "description": (
            "TODO/voice_fixed.jsx (517L, CC=68) to stara wersja.\n"
            "src/proxym/dashboard/components/voice.jsx (485L, CC=70) to aktualna.\n"
            "Usuń TODO/ wersję i zrefaktoryzuj aktualną."
        ),
        "type": "fix",
        "priority": "medium",
        "tags": ["cleanup", "voice"],
        "tool": "aider",
    },
    {
        "title": "CI: GitHub Actions — lint + unit tests on push",
        "description": (
            "Dodaj .github/workflows/ci.yml:\n"
            "  - ruff check + format\n"
            "  - pytest (bez GUI i live testów)\n"
            "  - E2E z Redis service container na PR"
        ),
        "type": "feature",
        "priority": "medium",
        "tags": ["ci", "github-actions", "devops"],
        "tool": "vscode",
    },
    {
        "title": "Tool executor: uruchom aider/claude-code na ticket",
        "description": (
            "Moduł proxym.tools.executor:\n"
            "  - executor.dispatch(ticket, tool='aider')\n"
            "  - Generuj prompt z ticket.description + context\n"
            "  - Uruchom narzędzie w odpowiednim projekcie\n"
            "  - Zapisz wynik jako komentarz do ticketu"
        ),
        "type": "feature",
        "priority": "medium",
        "tags": ["tools", "automation", "aider", "claude-code"],
        "tool": "claude-code",
    },
]


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--base", default=BASE)
    parser.add_argument("--key", default=KEY)
    parser.add_argument("--dry-run", action="store_true")
    args = parser.parse_args()

    base = args.base.rstrip("/")
    headers = {"X-Api-Key": args.key, "Content-Type": "application/json"}

    if args.dry_run:
        print(f"[DRY RUN] Would create sprint: {SPRINT['name']}")
        for i, t in enumerate(TICKETS, 1):
            print(f"  [{i:2d}] [{t['priority']:8s}] [{t['tool']:11s}] {t['title']}")
        return

    # Check proxy
    try:
        r = httpx.get(f"{base}/health", timeout=3)
        r.raise_for_status()
    except Exception as e:
        print(f"ERROR: Proxy not reachable at {base}: {e}")
        sys.exit(1)

    # Create sprint
    r = httpx.post(f"{base}/dashboard/sprints", json=SPRINT, headers=headers)
    if r.status_code not in (200, 201):
        print(f"ERROR creating sprint: {r.status_code} {r.text}")
        sys.exit(1)
    sprint_id = r.json()["id"]
    print(f"✅ Sprint created: {sprint_id} — {SPRINT['name']}")

    # Create tickets
    created = 0
    for t in TICKETS:
        tool = t.pop("tool", None)
        payload = {**t, "sprint_id": sprint_id}
        r = httpx.post(f"{base}/dashboard/tickets", json=payload, headers=headers)
        if r.status_code not in (200, 201):
            print(f"  ❌ Failed: {t['title']} — {r.status_code} {r.text}")
            continue
        tid = r.json()["id"]

        # Assign tool
        if tool:
            r2 = httpx.post(
                f"{base}/dashboard/tickets/{tid}/assign-tool",
                json={"tool": tool},
                headers=headers,
            )
            tool_status = "✅" if r2.status_code == 200 else "⚠️"
        else:
            tool_status = "—"

        print(f"  ✅ {tid} [{t['priority']:8s}] {tool_status} {tool or 'unassigned':11s} {t['title']}")
        created += 1

    print(f"\n{'='*60}")
    print(f"Sprint: {sprint_id}")
    print(f"Tickets: {created}/{len(TICKETS)} created")
    print(f"Board:   {base}/dashboard → tab Tickets")


if __name__ == "__main__":
    main()
