"""
Genesis Gold Pipeline — Domain Portfolio Activator
====================================================
Batch generates and deploys landing pages for the Genesis domain portfolio.
Processes domains in priority order (lowest tier first), generates pages
via Gemini, and deploys to Netlify.

Usage:
    # Activate all Tier 4-7 domains (city + trade + industry + voice)
    python domain_activator.py --max-tier 7

    # Activate just one domain
    python domain_activator.py --domain tradiechatbots.com.au

    # Dry run (generate but don't deploy)
    python domain_activator.py --max-tier 5 --dry-run

    # Generate with fallback only (no Gemini API needed)
    python domain_activator.py --max-tier 5 --fallback-only
"""

import argparse
import json
import logging
import time
import sys
from pathlib import Path
from datetime import datetime, timezone
from typing import Optional

sys.path.insert(0, str(Path(__file__).parent))
sys.path.insert(0, "/mnt/e/genesis-system/scripts/clone_pipeline")

from prompt_templates import get_domain_config, get_priority_domains, DOMAIN_MAP
from generate_site import generate_landing_page

logger = logging.getLogger("gold_pipeline.domain_activator")

# ---------------------------------------------------------------------------
# Output and reporting paths
# ---------------------------------------------------------------------------

OUTPUT_DIR = Path("/mnt/e/genesis-system/scripts/gold_pipeline/output")
REPORT_DIR = Path("/mnt/e/genesis-system/hive/progress")
ACTIVATION_LOG = OUTPUT_DIR / "activation_log.jsonl"


# ---------------------------------------------------------------------------
# Deploy to Netlify (reuse existing deployer)
# ---------------------------------------------------------------------------

def _deploy_to_netlify(html: str, domain: str) -> Optional[str]:
    """Deploy HTML to Netlify using the existing clone_pipeline deployer."""
    try:
        from deployer import deploy_to_netlify as netlify_deploy
        site_name = domain.replace(".", "-").replace("_", "-")
        url = netlify_deploy(html, site_name=site_name)
        return url
    except ImportError:
        logger.warning("Netlify deployer not available — saving locally only")
        return None
    except Exception as e:
        logger.error(f"Netlify deployment failed for {domain}: {e}")
        return None


# ---------------------------------------------------------------------------
# Save HTML locally
# ---------------------------------------------------------------------------

def _save_locally(html: str, domain: str) -> Path:
    """Save generated HTML to local output directory."""
    domain_dir = OUTPUT_DIR / domain
    domain_dir.mkdir(parents=True, exist_ok=True)
    output_path = domain_dir / "index.html"
    output_path.write_text(html, encoding="utf-8")

    # Also save a _redirects file for Netlify SPA support
    redirects_path = domain_dir / "_redirects"
    redirects_path.write_text("/* /index.html 200\n", encoding="utf-8")

    # And robots.txt
    robots_path = domain_dir / "robots.txt"
    robots_path.write_text(f"User-agent: *\nAllow: /\nSitemap: https://{domain}/sitemap.xml\n", encoding="utf-8")

    return output_path


# ---------------------------------------------------------------------------
# Log activation
# ---------------------------------------------------------------------------

def _log_activation(domain: str, status: str, html_chars: int = 0,
                    netlify_url: str = "", error: str = "", elapsed_secs: float = 0):
    """Append an activation record to the JSONL log."""
    ACTIVATION_LOG.parent.mkdir(parents=True, exist_ok=True)
    record = {
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "domain": domain,
        "status": status,
        "html_chars": html_chars,
        "netlify_url": netlify_url,
        "error": error,
        "elapsed_secs": round(elapsed_secs, 2),
    }
    with open(ACTIVATION_LOG, "a") as f:
        f.write(json.dumps(record) + "\n")


# ---------------------------------------------------------------------------
# Activate a single domain
# ---------------------------------------------------------------------------

def activate_domain(
    domain: str,
    model: str = "gemini-2.5-flash",
    deploy: bool = True,
    fallback_only: bool = False,
) -> dict:
    """
    Generate and optionally deploy a landing page for a single domain.

    Returns dict with: domain, status, html_chars, local_path, netlify_url, elapsed_secs
    """
    start = time.time()
    config = get_domain_config(domain)

    logger.info(f"--- Activating {domain} (vertical={config['vertical_key']}, tier={config['tier']}) ---")

    result = {
        "domain": domain,
        "vertical": config["vertical_key"],
        "tier": config["tier"],
        "status": "pending",
        "html_chars": 0,
        "local_path": "",
        "netlify_url": "",
        "error": "",
        "elapsed_secs": 0,
    }

    try:
        # Generate landing page
        if fallback_only:
            from generate_site import _generate_fallback, _inject_voice_widget, _inject_analytics
            html = _generate_fallback(config)
            html = _inject_voice_widget(html, config)
            html = _inject_analytics(html, domain)
        else:
            html = generate_landing_page(domain, model=model, use_fallback_on_failure=True)

        if not html:
            result["status"] = "failed"
            result["error"] = "Generation returned None"
            elapsed = time.time() - start
            result["elapsed_secs"] = elapsed
            _log_activation(domain, "failed", error="Generation returned None", elapsed_secs=elapsed)
            return result

        result["html_chars"] = len(html)

        # Save locally
        local_path = _save_locally(html, domain)
        result["local_path"] = str(local_path)
        logger.info(f"Saved: {local_path} ({len(html)} chars)")

        # Deploy to Netlify
        if deploy:
            netlify_url = _deploy_to_netlify(html, domain)
            if netlify_url:
                result["netlify_url"] = netlify_url
                result["status"] = "deployed"
                logger.info(f"Deployed: {netlify_url}")
            else:
                result["status"] = "generated"
                logger.warning(f"Local only (Netlify deployment skipped/failed)")
        else:
            result["status"] = "generated"

    except Exception as e:
        result["status"] = "error"
        result["error"] = str(e)
        logger.error(f"Error activating {domain}: {e}")

    elapsed = time.time() - start
    result["elapsed_secs"] = round(elapsed, 2)

    _log_activation(
        domain=domain,
        status=result["status"],
        html_chars=result["html_chars"],
        netlify_url=result["netlify_url"],
        error=result["error"],
        elapsed_secs=elapsed,
    )

    return result


# ---------------------------------------------------------------------------
# Batch activation
# ---------------------------------------------------------------------------

def activate_batch(
    domains: list,
    model: str = "gemini-2.5-flash",
    deploy: bool = True,
    fallback_only: bool = False,
    delay_between: float = 2.0,
) -> list:
    """
    Activate multiple domains sequentially.

    Args:
        domains: List of domain names
        model: Gemini model
        deploy: Whether to deploy to Netlify
        fallback_only: Use fallback templates only (no API calls)
        delay_between: Seconds to wait between domains (rate limiting)

    Returns:
        List of result dicts
    """
    results = []
    total = len(domains)
    success = 0
    failed = 0

    logger.info(f"=== GOLD PIPELINE: Activating {total} domains ===")
    batch_start = time.time()

    for i, domain in enumerate(domains, 1):
        logger.info(f"[{i}/{total}] Processing {domain}...")

        result = activate_domain(
            domain=domain,
            model=model,
            deploy=deploy,
            fallback_only=fallback_only,
        )

        results.append(result)

        if result["status"] in ("deployed", "generated"):
            success += 1
        else:
            failed += 1

        logger.info(f"[{i}/{total}] {domain}: {result['status']} ({result['elapsed_secs']}s)")

        # Rate limiting between API calls
        if i < total and not fallback_only:
            time.sleep(delay_between)

    batch_elapsed = time.time() - batch_start

    logger.info(f"=== BATCH COMPLETE: {success} success, {failed} failed, {round(batch_elapsed, 1)}s total ===")

    return results


# ---------------------------------------------------------------------------
# Generate batch report
# ---------------------------------------------------------------------------

def generate_report(results: list) -> str:
    """Generate a markdown report of the batch activation."""
    now = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
    deployed = [r for r in results if r["status"] == "deployed"]
    generated = [r for r in results if r["status"] == "generated"]
    failed = [r for r in results if r["status"] in ("failed", "error")]

    report = f"""# Gold Pipeline — Domain Activation Report
## Generated: {now}

### Summary
| Metric | Count |
|--------|-------|
| Total domains processed | {len(results)} |
| Successfully deployed | {len(deployed)} |
| Generated (local only) | {len(generated)} |
| Failed | {len(failed)} |
| Total HTML generated | {sum(r['html_chars'] for r in results):,} chars |
| Total time | {sum(r['elapsed_secs'] for r in results):.1f}s |

### Deployed Sites
| Domain | URL | Chars | Time |
|--------|-----|-------|------|
"""
    for r in deployed:
        report += f"| {r['domain']} | [{r['netlify_url']}]({r['netlify_url']}) | {r['html_chars']:,} | {r['elapsed_secs']}s |\n"

    if generated:
        report += "\n### Generated (Local Only)\n| Domain | Path | Chars | Time |\n|--------|------|-------|------|\n"
        for r in generated:
            report += f"| {r['domain']} | `{r['local_path']}` | {r['html_chars']:,} | {r['elapsed_secs']}s |\n"

    if failed:
        report += "\n### Failed\n| Domain | Error | Time |\n|--------|-------|------|\n"
        for r in failed:
            report += f"| {r['domain']} | {r['error'][:80]} | {r['elapsed_secs']}s |\n"

    report += f"""
### Next Steps
1. Configure DNS for deployed domains (CNAME → Netlify)
2. Test voice widget on each deployed page
3. Submit to Google Search Console for indexing
4. Set up Plausible analytics dashboard
5. Create spore URLs for outreach campaigns

### Domain Portfolio Status
- Total domains in portfolio: {len(DOMAIN_MAP)}
- Activated this batch: {len(results)}
- Deployment rate: {len(deployed)}/{len(DOMAIN_MAP)} ({len(deployed)/max(len(DOMAIN_MAP),1)*100:.0f}%)
"""
    return report


# ---------------------------------------------------------------------------
# CLI entry point
# ---------------------------------------------------------------------------

def main():
    parser = argparse.ArgumentParser(
        description="Genesis Gold Pipeline — Domain Portfolio Activator",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  # Activate all priority domains (Tier 4-7)
  python domain_activator.py --max-tier 7

  # Activate a single domain
  python domain_activator.py --domain tradiechatbots.com.au

  # Dry run — generate but don't deploy
  python domain_activator.py --max-tier 5 --dry-run

  # Fallback templates only (no Gemini API needed)
  python domain_activator.py --max-tier 7 --fallback-only

  # List all domains by priority
  python domain_activator.py --list
        """
    )
    parser.add_argument("--domain", help="Activate a single domain")
    parser.add_argument("--max-tier", type=int, default=7, help="Maximum tier to activate (default: 7)")
    parser.add_argument("--model", default="gemini-2.5-flash", help="Gemini model (default: gemini-2.5-flash)")
    parser.add_argument("--dry-run", action="store_true", help="Generate but don't deploy to Netlify")
    parser.add_argument("--fallback-only", action="store_true", help="Use fallback templates (no API calls)")
    parser.add_argument("--delay", type=float, default=2.0, help="Seconds between API calls (default: 2)")
    parser.add_argument("--list", action="store_true", help="List all domains by priority and exit")
    parser.add_argument("--report", action="store_true", help="Generate report from activation log")

    args = parser.parse_args()

    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s %(levelname)s %(name)s: %(message)s",
        datefmt="%H:%M:%S",
    )

    if args.list:
        print("\n=== Genesis Domain Portfolio (by priority) ===\n")
        for tier in range(1, 10):
            tier_domains = [d for d, c in DOMAIN_MAP.items() if c["tier"] == tier]
            if tier_domains:
                print(f"Tier {tier}:")
                for d in sorted(tier_domains):
                    config = get_domain_config(d)
                    city = config.get("city_key", "")
                    print(f"  {d:45s} vertical={config['vertical_key']:15s} city={city or 'national'}")
                print()
        print(f"Total: {len(DOMAIN_MAP)} domains")
        return

    if args.domain:
        # Single domain activation
        result = activate_domain(
            domain=args.domain,
            model=args.model,
            deploy=not args.dry_run,
            fallback_only=args.fallback_only,
        )
        print(f"\nResult: {json.dumps(result, indent=2)}")

    else:
        # Batch activation
        domains = get_priority_domains(max_tier=args.max_tier)
        if not domains:
            print(f"No domains found with tier <= {args.max_tier}")
            return

        print(f"\nActivating {len(domains)} domains (tier <= {args.max_tier}):")
        for d in domains:
            config = get_domain_config(d)
            print(f"  [{config['tier']}] {d}")

        results = activate_batch(
            domains=domains,
            model=args.model,
            deploy=not args.dry_run,
            fallback_only=args.fallback_only,
            delay_between=args.delay,
        )

        # Generate and save report
        report = generate_report(results)
        report_path = REPORT_DIR / f"gold_pipeline_activation_{datetime.now().strftime('%Y%m%d_%H%M')}.md"
        report_path.parent.mkdir(parents=True, exist_ok=True)
        report_path.write_text(report, encoding="utf-8")
        print(f"\nReport saved: {report_path}")

        # Summary
        deployed = sum(1 for r in results if r["status"] == "deployed")
        generated = sum(1 for r in results if r["status"] == "generated")
        failed = sum(1 for r in results if r["status"] in ("failed", "error"))
        print(f"\nSummary: {deployed} deployed, {generated} local only, {failed} failed")


if __name__ == "__main__":
    main()
