"""ievo cortex — Cortex kernel management commands.

ievo cortex build   Rebuild Cortex artifacts locally from source.

# TODO: ievo cortex update — separate REQ
"""

from __future__ import annotations

import subprocess
import sys
from pathlib import Path

import typer

from ievo.core.config import CACHE_DIR, require_project
from ievo.utils.console import error, info, step, success

app = typer.Typer(name="cortex", help="Cortex kernel management.")

CORTEX_REPO_URL = "https://github.com/ievo-ai/cortex.git"
CORTEX_CACHE_DIR: Path = CACHE_DIR / "cortex"


@app.command()
def build() -> None:
    """Rebuild Cortex artifacts locally from the Cortex source repo.

    Clones (or updates) ievo-ai/cortex to ~/.ievo/cache/cortex/,
    runs the Cortex build script, and writes artifacts to .ievo/cortex/.
    """
    root = require_project()

    info("[bold]Cortex build[/bold]")

    # ── Step 1: Clone or update the Cortex repo ───────────────
    if CORTEX_CACHE_DIR.exists() and (CORTEX_CACHE_DIR / ".git").exists():
        info("Using cached Cortex clone — pulling latest...")
        result = subprocess.run(
            ["git", "pull", "--ff-only"],
            cwd=CORTEX_CACHE_DIR,
            capture_output=True,
            text=True,
        )
        if result.returncode != 0:
            error(f"git pull failed:\n{result.stderr}")
            raise typer.Exit(1)
        step("git pull OK")
    else:
        CORTEX_CACHE_DIR.parent.mkdir(parents=True, exist_ok=True)
        info(f"Cloning {CORTEX_REPO_URL}...")
        result = subprocess.run(
            ["git", "clone", CORTEX_REPO_URL, str(CORTEX_CACHE_DIR)],
            capture_output=True,
            text=True,
        )
        if result.returncode != 0:
            error(f"git clone failed:\n{result.stderr}")
            raise typer.Exit(1)
        step("git clone OK")

    # ── Step 2: Get the current tag ──────────────────────────
    tag_result = subprocess.run(
        ["git", "describe", "--tags", "--abbrev=0"],
        cwd=CORTEX_CACHE_DIR,
        capture_output=True,
        text=True,
    )
    tag = tag_result.stdout.strip() if tag_result.returncode == 0 else "dev"

    # ── Step 3: Run the build script ─────────────────────────
    cortex_output_dir = root / ".ievo" / "cortex"
    build_script = CORTEX_CACHE_DIR / "build.py"

    info(f"Building Cortex {tag}...")
    build_result = subprocess.run(
        [sys.executable, str(build_script), "--tag", tag, "--dist", str(cortex_output_dir)],
        cwd=CORTEX_CACHE_DIR,
        capture_output=True,
        text=True,
    )
    if build_result.returncode != 0:
        error(f"Cortex build failed:\n{build_result.stderr}")
        raise typer.Exit(1)
    step(f"built to {cortex_output_dir}")

    # ── Step 4: Write version file ───────────────────────────
    version_file = root / ".ievo" / "cortex-version"
    version_file.write_text(tag + "\n")
    step(f"cortex-version = {tag}")

    success(f"Cortex {tag} built successfully.")
