"""Link a Gjalla account and project to an existing local setup."""

import json
import os
from pathlib import Path

import click
from rich.prompt import Prompt

from ..display.output import console, success, error, warning, info, panel
from ._shared import get_repo_root, load_local_config, save_local_config, local_config_exists
from ._api import verify_api_key, discover_or_select_project


@click.command()
@click.option(
    "--api-key",
    envvar="GJALLA_API_KEY",
    help="API key for gjalla cloud. Can also be set via GJALLA_API_KEY env var.",
)
@click.option(
    "--project-id",
    type=int,
    help="Project ID to link. If omitted, auto-discover or prompt.",
)
def connect(api_key: str | None, project_id: int | None) -> None:
    """Link a Gjalla account and project to this repository.

    \b
    Requires 'gjalla init' to have been run first (.gjalla/ must exist).
    Updates .gjalla/config.json with the project_id, saves the API key
    to global config, and syncs any pending local attestations.

    \b
    Examples:
        gjalla connect                          # Interactive
        gjalla connect --api-key gj_... --project-id 46
    """
    repo_root = get_repo_root()
    gjalla_dir = repo_root / ".gjalla"

    if not gjalla_dir.is_dir():
        error("No .gjalla/ directory found. Run 'gjalla init' first.")
        raise SystemExit(1)

    if not local_config_exists(repo_root):
        error("No .gjalla/config.yaml found. Run 'gjalla init' first.")
        raise SystemExit(1)

    panel("Link Gjalla Account", title="gjalla connect")
    console.print()

    # Load existing project config
    project_config = load_local_config(repo_root)

    api_url = os.environ.get("GJALLA_API_URL") or project_config.get("api_url", "https://gjalla.io")

    # Get API key
    if not api_key:
        # Check global config
        from .init import load_global_config
        global_config = load_global_config()
        if global_config.get("api_key"):
            api_key = global_config["api_key"]
            info("Using existing API key from global config")
        else:
            api_key = Prompt.ask("[bold]Enter your gjalla API key[/bold]", password=True)

    if not api_key:
        error("API key is required. Get one at https://gjalla.io/settings/api")
        raise SystemExit(1)

    # Verify
    info("Verifying API key...")
    key_ok, key_detail = verify_api_key(api_key, api_url)
    if not key_ok:
        error(f"API key verification failed — {key_detail}")
        info("  Tip: You can find your API key at https://gjalla.io/settings")
        info("  Run 'gjalla connect --api-key <key>' to retry with a new key")
        raise SystemExit(1)
    success("API key verified")
    console.print()

    # Discover/select project
    project_info = discover_or_select_project(repo_root, api_key, api_url, project_id)
    if not project_info:
        raise SystemExit(1)

    success(f"Selected project: {project_info.get('name', project_info['id'])}")
    console.print()

    # Update .gjalla/config.yaml
    project_config["project_id"] = project_info["id"]
    project_config["api_url"] = api_url
    save_local_config(repo_root, project_config)
    success("Updated .gjalla/config.yaml")

    # Save API key to global config
    from .init import load_global_config, save_global_config
    global_config = load_global_config()
    global_config["api_key"] = api_key
    global_config["api_url"] = api_url
    if "projects" not in global_config:
        global_config["projects"] = {}
    global_config["projects"][str(repo_root)] = str(project_info["id"])
    save_global_config(global_config)
    success("Saved API key to global config")
    console.print()

    # Sync pending attestations
    info("Syncing pending attestations...")
    from ..config.settings import Settings
    from .sync import _upload_attestations
    settings = Settings.load()
    attestations_dir = repo_root / ".gjalla" / "attestations"
    _upload_attestations(settings, repo_root, attestations_dir)

    console.print()
    panel(
        f"[green]Connected to project {project_info.get('name', project_info['id'])}[/green]\n\n"
        "Attestations will now upload automatically after each commit.",
        title="gjalla connected!",
    )
