from __future__ import annotations

import re
from datetime import datetime
from typing import Any

from exo.kernel.utils import gen_timestamp_id

TASK_RE = re.compile(r"^\*\s+(T\d+):\s+(.+)$", re.MULTILINE)
EPIC_RE = re.compile(r"^###\s+(EPIC-\d+):\s+(.+)$", re.MULTILINE)


def _build_spec_markdown(input_text: str) -> str:
    now = datetime.now().astimezone().isoformat(timespec="seconds")
    spec_id = gen_timestamp_id("SPEC")
    return (
        f"# {spec_id}\n\n"
        f"Generated at {now}.\n\n"
        "## Input\n\n"
        f"{input_text.strip()}\n\n"
        "## Notes\n\n"
        "- Generated by default planner (LLM-free mode).\n"
    )


def _extract_seed_tickets(input_text: str) -> list[dict[str, Any]]:
    tickets: list[dict[str, Any]] = []
    epic = EPIC_RE.search(input_text)
    parent_id = None

    if epic:
        parent_id = gen_timestamp_id("TKT") + "-EPIC"
        tickets.append(
            {
                "id": parent_id,
                "type": "feature",
                "title": f"{epic.group(1)}: {epic.group(2)}",
                "status": "todo",
                "priority": 5,
                "parent_id": None,
                "scope": {
                    "allow": ["**"],
                    "deny": [".env*", "**/.ssh/**", "**/.aws/**", ".git/**"],
                },
                "budgets": {
                    "max_files_changed": 12,
                    "max_loc_changed": 400,
                },
                "checks": [],
                "notes": ["Generated from planning input."],
                "blockers": [],
                "labels": ["epic"],
            }
        )

    tasks = TASK_RE.findall(input_text)
    for _, title in tasks[:6]:
        tickets.append(
            {
                "id": gen_timestamp_id("TKT"),
                "type": "feature",
                "title": title.strip(),
                "status": "todo",
                "priority": 4,
                "parent_id": parent_id,
                "scope": {
                    "allow": ["**"],
                    "deny": [".env*", "**/.ssh/**", "**/.aws/**", ".git/**"],
                },
                "budgets": {
                    "max_files_changed": 12,
                    "max_loc_changed": 400,
                },
                "checks": [],
                "notes": ["Generated from planning input."],
                "blockers": [],
                "labels": ["planned"],
            }
        )

    if tickets:
        return tickets

    return [
        {
            "type": "feature",
            "title": "Implement planned work item",
            "status": "todo",
            "priority": 3,
            "scope": {"allow": ["**"], "deny": [".env*", ".git/**"]},
            "budgets": {"max_files_changed": 8, "max_loc_changed": 250},
            "checks": [],
            "notes": ["Fallback planner ticket."],
            "blockers": [],
            "labels": ["planned"],
        }
    ]


def run(payload: dict[str, Any]) -> dict[str, Any]:
    input_text = str(payload.get("input", "")).strip()
    return {
        "spec_markdown": _build_spec_markdown(input_text),
        "tickets": _extract_seed_tickets(input_text),
    }
