"""SEO Report CLI entry point."""

import os
from pathlib import Path
from typing import Optional

import typer
from jinja2 import Environment, FileSystemLoader

from worai.core.profile_loader import load_profile
from worai.seoreport.core import ReportOptions, generate_report_data

app = typer.Typer(add_completion=False, no_args_is_help=True)

def _resolve_value(
    ctx: typer.Context,
    value: str | None,
    path: str,
    env_key: str | None,
) -> str | None:
    if value:
        return value
    if env_key and env_key in os.environ:
        return os.environ[env_key]
    try:
        profile, _, _ = load_profile(ctx)
    except ValueError:
        return None
    profile_settings = getattr(profile, "settings", {}) or {}
    underscore_key = path.replace(".", "_")
    if underscore_key in profile_settings:
        return profile_settings[underscore_key]
    if path in profile_settings:
        return profile_settings[path]
    return None

@app.callback(invoke_without_command=True)
def run(
    ctx: typer.Context,
    site: Optional[str] = typer.Option(None, "--site", help="GSC property URL (or gsc.id in config)."),
    url_regex: Optional[str] = typer.Option(None, "--url-regex", help="Regex to filter URLs."),
    output: Optional[str] = typer.Option(None, "--output", help="Output file path."),
    format: str = typer.Option("markdown", "--format", help="Output format: markdown or html."),
    client_secrets: Optional[str] = typer.Option(None, "--client-secrets", help="OAuth2 client secrets JSON."),
    token: Optional[str] = typer.Option(None, "--token", help="Path to store OAuth2 token."),
    ga_id: Optional[str] = typer.Option(None, "--ga-id", help="GA4 property ID for Analytics section."),
    ga_client_secrets: Optional[str] = typer.Option(None, "--ga-client-secrets", help="OAuth2 client secrets JSON for GA4."),
    ga_token: Optional[str] = typer.Option(None, "--ga-token", help="Deprecated. Use --token for shared OAuth token."),
    ga_direct_share: float = typer.Option(0.3, "--ga-direct-share", help="Share of Direct traffic reallocated to AI (0-1)."),
    ga_source_regex: str = typer.Option("(chatgpt|openai|gemini|copilot|perplexity)", "--ga-source-regex", help="Regex to detect AI traffic from GA4 source."),
    ga_channel_group_name: str = typer.Option("AI Channel Group", "--ga-channel-group-name", help="GA4 custom channel group name for AI traffic."),
    ga_channel_group_id: Optional[str] = typer.Option(None, "--ga-channel-group-id", help="GA4 custom channel group ID for AI traffic."),
    gsc_max_workers: int = typer.Option(3, "--gsc-max-workers", help="Max parallel workers for GSC requests."),
    ga_max_workers: int = typer.Option(3, "--ga-max-workers", help="Max parallel workers for GA4 requests."),
    port: int = typer.Option(8080, "--port", help="Local redirect port for OAuth flow."),
    inspect_limit: int = typer.Option(0, "--inspect-limit", help="Number of top pages to inspect (0 skips, GSC quota)."),
) -> None:
    """Generate SEO performance report."""
    
    # Resolve credentials/config
    resolved_site = _resolve_value(ctx, site, "gsc.id", "GSC_ID")
    if not resolved_site:
        raise typer.BadParameter("--site is required (or set profiles.<name>.gsc.id / GSC_ID).")

    resolved_client_secrets = _resolve_value(
        ctx,
        client_secrets,
        "gsc.client_secrets",
        "GSC_CLIENT_SECRETS",
    )
    resolved_token = (
        _resolve_value(ctx, token, "oauth.token", "OAUTH_TOKEN")
        or _resolve_value(ctx, token, "gsc.token", "GSC_TOKEN")
        or _resolve_value(ctx, token, "ga.token", "GA_TOKEN")
        or "oauth_token.json"
    )
    resolved_ga_id = _resolve_value(ctx, ga_id, "ga.id", "GA_ID")
    resolved_ga_client_secrets = _resolve_value(
        ctx,
        ga_client_secrets,
        "ga.client_secrets",
        "GA_CLIENT_SECRETS",
    ) or resolved_client_secrets
    resolved_ga_token = _resolve_value(ctx, ga_token, "ga.token", "GA_TOKEN")
    if token and ga_token and token != ga_token:
        raise typer.BadParameter("--token and --ga-token must point to the same file (single-token mode).")
    if resolved_ga_token and resolved_ga_token != resolved_token:
        raise typer.BadParameter("--ga-token must match --token (single-token mode).")
    resolved_ga_token = resolved_token
    
    # Default output filename
    if not output:
        ext = "html" if format == "html" else "md"
        timestamp = generate_timestamp_str()
        output = f"seo_report_{timestamp}.{ext}"

    options = ReportOptions(
        site=resolved_site,
        url_regex=url_regex,
        client_secrets=resolved_client_secrets,
        token=resolved_token,
        ga_id=resolved_ga_id,
        ga_client_secrets=resolved_ga_client_secrets,
        ga_token=resolved_ga_token,
        ga_direct_share=ga_direct_share,
        ga_source_regex=ga_source_regex,
        ga_channel_group_name=ga_channel_group_name,
        ga_channel_group_id=ga_channel_group_id,
        gsc_max_workers=gsc_max_workers,
        ga_max_workers=ga_max_workers,
        port=port,
        output=output,
        format=format,
        inspect_limit=inspect_limit
    )

    typer.echo(f"Generating {format} report for {resolved_site}...")
    
    try:
        if options.ga_direct_share < 0 or options.ga_direct_share > 1:
            raise typer.BadParameter("--ga-direct-share must be between 0 and 1.")
        data = generate_report_data(options)
        
        # Render
        template_dir = Path(__file__).parent / "templates"
        env = Environment(loader=FileSystemLoader(template_dir))
        
        template_name = "report.html" if format == "html" else "report.md"
        template = env.get_template(template_name)
        
        rendered = template.render(data=data)
        
        with open(output, "w", encoding="utf-8") as f:
            f.write(rendered)
            
        typer.echo(f"Report saved to: {output}")
        
    except Exception as e:
        typer.echo(f"Error generating report: {e}", err=True)
        raise typer.Exit(code=1)

def generate_timestamp_str():
    import datetime
    return datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
