"""complyform feedback command — open GitHub Issues with diagnostics."""

from __future__ import annotations

import json
import sys
import urllib.parse
import webbrowser
from typing import Annotated

import typer

from complyform.cli.main import AppContext, app

_MG = "Management"

_REPO_URL = "https://github.com/complyform/complyform"


@app.command(name="feedback", rich_help_panel=_MG)
def feedback_cmd(
    ctx: typer.Context,
    bug: Annotated[
        bool,
        typer.Option(
            "--bug",
            help=("Open bug report template (default if no flag)."),
        ),
    ] = False,
    feature: Annotated[
        bool,
        typer.Option("--feature", help="Open feature request template."),
    ] = False,
    title: Annotated[
        str | None,
        typer.Option("--title", "-t", help="Pre-fill issue title."),
    ] = None,
    format: Annotated[
        str,
        typer.Option(
            "--format",
            "-f",
            help="Output format: terminal|json.",
        ),
    ] = "terminal",
    output: Annotated[
        str | None,
        typer.Option(
            "--output",
            "-o",
            help="Write output to file.",
        ),
    ] = None,
) -> None:
    """Submit feedback or bug reports."""
    app_ctx: AppContext = ctx.obj

    from complyform.cli.doctor_cmd import build_diagnostic_string

    diag = build_diagnostic_string(
        tier=app_ctx.config.tier,
        cloud=app_ctx.config.default_cloud,
    )

    # Select template — bug is default
    template = "feature_request.yaml" if feature and not bug else "bug_report.yaml"

    # Build URL
    params: dict[str, str] = {
        "template": template,
        "body": diag,
    }
    if title:
        params["title"] = title

    url = (
        f"{_REPO_URL}/issues/new?"
        f"{urllib.parse.urlencode(params, quote_via=urllib.parse.quote)}"
    )

    if format == "json":
        envelope = {"url": url, "diagnostics": diag}
        text = json.dumps(envelope, indent=2)
        if output:
            from pathlib import Path

            Path(output).write_text(text, encoding="utf-8")
        else:
            sys.stdout.write(text + "\n")
        raise typer.Exit(code=0)

    # Terminal mode
    opened = False
    if sys.stdout.isatty():
        opened = webbrowser.open(url)

    console = app_ctx.console
    if opened:
        console.print("Opened GitHub Issues in your browser.")
    else:
        console.print(f"Open this URL to file your report:\n  {url}")

    raise typer.Exit(code=0)
