"""CLI command: asa spec infer — generate draft .asa/spec.yaml from existing repo."""

from pathlib import Path

import typer

from ...core import logging as log
from ...core.fs import safe_write_file
from ...core.paths import find_project_root
from ...engine.spec.inferrer import infer_spec
from ...engine.spec.parser import spec_to_yaml

SPEC_DIR = ".asa"
SPEC_FILENAME = "spec.yaml"


def spec_infer(
    path: str = typer.Argument(".", help="Path to project root (default: current directory)"),
    force: bool = typer.Option(False, "--force", "-f", help="Overwrite existing spec.yaml"),
) -> None:
    """Generate a draft .asa/spec.yaml from an existing repository.

    Scans the repo to detect framework, providers, domains, auth patterns,
    billing patterns, and inline entitlement checks. Generates a draft spec
    that requires manual review before use.
    """
    project_root = Path(path).resolve()

    if not project_root.exists():
        log.error(f"Path does not exist: {project_root}")
        raise typer.Exit(code=2)

    spec_path = project_root / SPEC_DIR / SPEC_FILENAME
    if spec_path.exists() and not force:
        log.error(
            f"Spec already exists: {spec_path}\n"
            f"   Use --force to overwrite, or edit the existing spec."
        )
        raise typer.Exit(code=1)

    # Infer spec from repo
    spec = infer_spec(project_root)

    # Serialize to YAML with header comments
    yaml_content = _build_spec_yaml(spec)

    # Write
    safe_write_file(spec_path, yaml_content, overwrite=force)
    log.success(f"Draft spec written to: {spec_path}")
    log.info("⚠️  Review the spec before running 'asa apply' or 'asa verify'.")
    log.detail("Look for TODO comments — they mark values that need manual verification.")


def _build_spec_yaml(spec) -> str:
    """Build spec.yaml content with header comments."""
    yaml_body = spec_to_yaml(spec)

    header = """# ASA Architecture Spec v0.1 — DRAFT (auto-inferred)
# This file was generated by 'asa spec infer' from your existing repository.
#
# ⚠️  REVIEW REQUIRED: This is a draft. Verify all values before using.
# Look for TODO comments — they mark values that need manual verification.
#
# After review, run:
#   asa plan      → see what changes will be made (dry-run)
#   asa apply     → apply foundation architecture
#   asa verify    → check architecture against this spec
#
# Docs: https://github.com/janvoldan/asa-standard

"""
    return header + yaml_body
