"""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 ..tools.git_tools import get_remote_url
from ._shared import get_repo_root
from ._api import verify_api_key, discover_project, select_project_interactively


@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)

    config_path = gjalla_dir / "config.json"
    if not config_path.exists():
        error("No .gjalla/config.json found. Run 'gjalla init' first.")
        raise SystemExit(1)

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

    # Load existing project config
    try:
        project_config = json.loads(config_path.read_text())
    except (json.JSONDecodeError, OSError):
        project_config = {}

    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...")
    if not verify_api_key(api_key, api_url):
        error("Invalid API key. Please check your key and try again.")
        raise SystemExit(1)
    success("API key verified")
    console.print()

    # Discover/select project
    project_info = None
    if project_id:
        info(f"Using provided project ID: {project_id}")
        project_info = {"id": project_id, "name": "unknown"}
    else:
        remote_url = get_remote_url(repo_root)
        if remote_url and not remote_url.startswith("Error:"):
            info(f"Found git remote: {remote_url}")
            discovered = discover_project(remote_url, api_key, api_url)
            if discovered:
                from rich.prompt import Confirm
                info(f"Discovered project: {discovered['name']}")
                if Confirm.ask("Is this the correct project?", default=True):
                    project_info = discovered

        if not project_info:
            info("Select your project:")
            project_info = select_project_interactively(api_key, api_url)
            if not project_info:
                raise SystemExit(1)

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

    # Update .gjalla/config.json
    project_config["project_id"] = project_info["id"]
    project_config["api_url"] = api_url
    config_path.write_text(json.dumps(project_config, indent=2) + "\n")
    success("Updated .gjalla/config.json")

    # 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!",
    )
