"""Project and upgrade CLI commands."""
from __future__ import annotations

from pathlib import Path
from typing import TYPE_CHECKING

import click

from ..utils.templates import PROJECT_TEMPLATES, copy_project_template
from ..utils.output import write_result_output

if TYPE_CHECKING:
    pass


UPGRADE_RELEASE_NOTES: dict[str, str] = {
    "0.2.0": "docs/releases/0.2.0.md",
    "0.3.0": "docs/releases/0.3.0.md",
}


def upgrade_steps(from_version: str, to_version: str) -> list[str]:
    """Get upgrade steps between versions."""
    steps = [
        f"Review release notes for {from_version} -> {to_version}",
        "Run `logos-adk upgrade checklist` and capture owners for each item",
        "Run `logos-adk storage upgrade-check` against every persistent backend",
        "Upgrade a staging deployment and run `pytest -q` plus smoke tests",
        "Roll out with workspace-scoped API keys and observability dashboards enabled",
    ]
    if from_version.startswith("0.1"):
        steps.insert(1, "Adopt `logos_adk.api` as the stable import root where possible")
    if to_version >= "0.3.0":
        steps.insert(2, "Review RBAC roles, secret rotation guidance, and multi-tenant architecture docs")
    return steps


@click.group()
def project() -> None:
    """Project management commands."""
    pass


@click.group(name="upgrade")
def upgrade_cli() -> None:
    """Upgrade planning and release-management commands."""
    pass


@project.command("new")
@click.argument("template", type=click.Choice(sorted(PROJECT_TEMPLATES)))
@click.argument("destination", type=click.Path(path_type=Path))
@click.option("--list-templates", is_flag=True, help="List available templates")
def project_new(template: str, destination: Path, list_templates: bool) -> None:
    """Create a new project from TEMPLATE at DESTINATION."""
    if list_templates:
        click.echo("Available templates:")
        for name in sorted(PROJECT_TEMPLATES):
            files = len(PROJECT_TEMPLATES[name])
            click.echo(f"  {name} ({files} files)")
        return
    
    if template not in PROJECT_TEMPLATES:
        click.echo(click.style(f"Error: Unknown template '{template}'", fg="red", err=True), err=True)
        click.echo(f"Available templates: {', '.join(sorted(PROJECT_TEMPLATES))}")
        raise SystemExit(1)
    
    created = copy_project_template(template, destination)
    
    click.echo(f"✓ Created project '{template}' at {destination}")
    for path in created:
        click.echo(f"  - {path.relative_to(destination)}")
    
    click.echo("\nNext steps:")
    click.echo(f"  cd {destination}")
    click.echo("  pip install -r requirements.txt  # if exists")
    click.echo("  logos-adk serve --agents agent.yaml")


def _emit_upgrade_plan(from_version: str, to_version: str, output: Path | None) -> None:
    steps = upgrade_steps(from_version, to_version)
    click.echo(f"Upgrade plan: {from_version} -> {to_version}\n")
    for i, step in enumerate(steps, 1):
        click.echo(f"{i}. {step}")
    click.echo("\nReferences:")
    click.echo("  - docs/upgrade-guide.md")
    if to_version in UPGRADE_RELEASE_NOTES:
        click.echo(f"  - {UPGRADE_RELEASE_NOTES[to_version]}")
    write_result_output(output, {
        "from_version": from_version,
        "to_version": to_version,
        "steps": steps,
        "guide": "docs/upgrade-guide.md",
        "release_notes": UPGRADE_RELEASE_NOTES.get(to_version),
    })


def _emit_release_notes(target_version: str) -> None:
    notes_path = UPGRADE_RELEASE_NOTES.get(target_version)
    if notes_path:
        click.echo(notes_path)
        return
    raise click.ClickException(
        f"No release notes found for {target_version}. Available: {', '.join(UPGRADE_RELEASE_NOTES)}"
    )


def _emit_upgrade_checklist() -> None:
    checklist = [
        "Review release notes for the target version",
        "Run `logos-adk upgrade plan --from-version <current> --to-version <target>`",
        "Run `logos-adk upgrade checklist` and assign owners",
        "Run `logos-adk storage upgrade-check` for every persistent backend",
        "Run smoke tests and staging verification",
        "Roll out and monitor logs, metrics, and alerts",
    ]
    click.echo("Upgrade checklist:\n")
    for i, item in enumerate(checklist, 1):
        click.echo(f"{i}. {item}")


@project.command("upgrade")
@click.option("--from-version", "from_version", required=True, help="Current deployed version")
@click.option("--to-version", "to_version", default="0.3.0", help="Target version")
@click.option("--output", "-o", type=click.Path(path_type=Path), help="Write JSON/YAML output")
def upgrade(from_version: str, to_version: str, output: Path | None) -> None:
    """Show upgrade steps from FROM_VERSION to TO_VERSION."""
    _emit_upgrade_plan(from_version, to_version, output)


@project.command()
@click.option("--version", "target_version", default="0.3.0", help="Version to inspect")
def releases(target_version: str) -> None:
    """Show release notes for a specific version."""
    _emit_release_notes(target_version)


@project.command("checklist")
def upgrade_checklist() -> None:
    """Show upgrade checklist."""
    _emit_upgrade_checklist()


@upgrade_cli.command("plan")
@click.option("--from-version", "from_version", required=True, help="Current deployed version")
@click.option("--to-version", "to_version", default="0.3.0", help="Target version")
@click.option("--output", "-o", type=click.Path(path_type=Path), help="Write JSON/YAML output")
def upgrade_plan(from_version: str, to_version: str, output: Path | None) -> None:
    """Show upgrade plan from FROM_VERSION to TO_VERSION."""
    _emit_upgrade_plan(from_version, to_version, output)


@upgrade_cli.command("release-notes")
@click.option("--version", "target_version", default="0.3.0", help="Version to inspect")
def upgrade_release_notes(target_version: str) -> None:
    """Print the release notes path for VERSION."""
    _emit_release_notes(target_version)


@upgrade_cli.command("checklist")
def upgrade_checklist_command() -> None:
    """Show the operational upgrade checklist."""
    _emit_upgrade_checklist()


__all__ = [
    "project",
    "project_new",
    "upgrade",
    "releases",
    "upgrade_checklist",
    "upgrade_cli",
    "upgrade_plan",
    "upgrade_release_notes",
    "upgrade_checklist_command",
]
