#!/usr/bin/env python3
"""
Bulk Domain 301 Redirect Script — Genesis Domain Empire
========================================================
Reads a CSV of domains + target URLs, sets 301 redirects via:
  - GoDaddy REST API (for GoDaddy-registered domains)
  - VentraIP Playwright automation (for VentraIP domains — no public API)
  - Namecheap XML API (for Namecheap domains)

Usage:
    python bulk_domain_redirect.py --input redirects.csv [--registrar godaddy|ventraip|namecheap|all]
    python bulk_domain_redirect.py --domain dentalbotai.au --target https://receptionistai.au --registrar ventraip

CSV Format (redirects.csv):
    domain,target_url,registrar
    dentalbotai.au,https://receptionistai.au,ventraip
    lawyerbot.au,https://receptionistai.au,ventraip
    sunaivasites.com.au,https://sunaiva.com,godaddy

Author: Genesis Domain Empire Agent
Date: 2026-02-23
"""

import csv
import sys
import time
import json
import argparse
import logging
from pathlib import Path
from typing import Optional

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    handlers=[
        logging.StreamHandler(),
        logging.FileHandler("E:/genesis-system/scripts/bulk_redirect_log.txt", mode="a")
    ]
)
log = logging.getLogger("domain_redirect")

# ============================================================
# CONFIGURATION — Update credentials before running
# ============================================================

GODADDY_CONFIG = {
    "api_key": "",       # From E:/genesis-system/Credentials/godaddy_api.txt
    "api_secret": "",    # From E:/genesis-system/Credentials/godaddy_api.txt
    "base_url": "https://api.godaddy.com/v1",
    "account_id": "108866004",
}

VENTRAIP_CONFIG = {
    "login_url": "https://vip.ventraip.com.au/login",
    "username": "",      # VentraIP login email
    "password": "",      # VentraIP password
    "headless": True,    # Set False to watch browser automation
}

NAMECHEAP_CONFIG = {
    "api_key": "",       # Namecheap API key
    "api_user": "Sunaiva",
    "client_ip": "",     # Whitelisted IP for API access
    "base_url": "https://api.namecheap.com/xml.response",
    "sandbox": False,
}

# GHL forwarding IP (domains that redirect via GHL subdomain forwarding)
GHL_FORWARD_IP = "3.130.4.74"

# Cloudflare API (preferred DNS management layer)
CLOUDFLARE_CONFIG = {
    "api_token": "",     # Cloudflare API token with Zone:Edit permissions
    "base_url": "https://api.cloudflare.com/client/v4",
}


def load_credentials():
    """Load credentials from the Genesis credentials store."""
    creds_path = Path("E:/genesis-system/Credentials/godaddy_api.txt")
    if creds_path.exists():
        with open(creds_path) as f:
            for line in f:
                if line.startswith("Key:"):
                    GODADDY_CONFIG["api_key"] = line.split(":", 1)[1].strip()
                elif line.startswith("Secret:"):
                    GODADDY_CONFIG["api_secret"] = line.split(":", 1)[1].strip()
        log.info("GoDaddy credentials loaded from credentials store.")


def load_csv(filepath: str) -> list[dict]:
    """Load redirect instructions from CSV file."""
    records = []
    with open(filepath, newline="") as f:
        reader = csv.DictReader(f)
        for row in reader:
            row["domain"] = row["domain"].strip().lower()
            row["target_url"] = row["target_url"].strip()
            row["registrar"] = row.get("registrar", "ventraip").strip().lower()
            records.append(row)
    log.info(f"Loaded {len(records)} redirect records from {filepath}")
    return records


# ============================================================
# STRATEGY 1: GoDaddy API — DNS-based URL forwarding
# ============================================================

def set_godaddy_redirect(domain: str, target_url: str) -> bool:
    """
    Set a 301 redirect on a GoDaddy domain using the DNS API.
    GoDaddy supports URL forwarding via their Forwarding API.

    Note: GoDaddy URL forwarding is set via the Domains Forwarding endpoint,
    not the DNS records endpoint. This creates a 301 redirect at the DNS layer.
    """
    try:
        import requests

        api_key = GODADDY_CONFIG["api_key"]
        api_secret = GODADDY_CONFIG["api_secret"]

        if not api_key or not api_secret:
            log.error("GoDaddy credentials not configured. Check GODADDY_CONFIG.")
            return False

        headers = {
            "Authorization": f"sso-key {api_key}:{api_secret}",
            "Content-Type": "application/json",
        }

        # GoDaddy URL Forwarding — sets 301 at domain level
        # Endpoint: PUT /v1/domains/{domain}/forwarding
        forward_url = f"{GODADDY_CONFIG['base_url']}/domains/{domain}/forwarding"

        payload = {
            "type": "REDIRECT",          # REDIRECT = 301 permanent
            "url": target_url,
            "maskPath": False,           # Don't mask (show target URL)
        }

        resp = requests.put(forward_url, json=payload, headers=headers, timeout=15)

        if resp.status_code in (200, 201, 204):
            log.info(f"[GODADDY OK] {domain} → 301 → {target_url}")
            return True
        else:
            log.error(f"[GODADDY FAIL] {domain} HTTP {resp.status_code}: {resp.text}")
            # Fallback: set DNS A record + Cloudflare redirect rule
            return set_godaddy_dns_redirect_fallback(domain, target_url, headers)

    except ImportError:
        log.error("requests library not installed. Run: pip install requests")
        return False
    except Exception as e:
        log.error(f"[GODADDY ERROR] {domain}: {e}")
        return False


def set_godaddy_dns_redirect_fallback(domain: str, target_url: str, headers: dict) -> bool:
    """
    Fallback: Set GoDaddy DNS A record pointing to a redirect server.
    This requires a redirect server at the target IP (e.g., nginx/Caddy with 301 rule).
    Alternative: Use Cloudflare proxy with Page Rules for 301 redirect.
    """
    import requests

    # For now, add an A record pointing to Cloudflare's redirect infrastructure
    # This must be combined with a Cloudflare Page Rule to do the actual 301
    log.warning(f"[GODADDY FALLBACK] {domain} — using DNS A record + Cloudflare redirect rule")

    dns_url = f"{GODADDY_CONFIG['base_url']}/domains/{domain}/records"
    records = [
        {"type": "A", "name": "@", "data": "192.0.2.1", "ttl": 600},
        {"type": "CNAME", "name": "www", "data": domain, "ttl": 600},
    ]

    resp = requests.patch(dns_url, json=records, headers=headers, timeout=15)
    if resp.status_code == 200:
        log.info(f"[GODADDY DNS] {domain} A record set — configure Cloudflare Page Rule for 301")
        return True
    else:
        log.error(f"[GODADDY DNS FAIL] {domain}: {resp.text}")
        return False


# ============================================================
# STRATEGY 2: VentraIP — Playwright browser automation
# ============================================================

def set_ventraip_redirect(domain: str, target_url: str) -> bool:
    """
    Set a 301 redirect on a VentraIP domain via VIPcontrol browser automation.
    VentraIP has no public retail API, so we use Playwright to automate the UI.

    VIPcontrol URL Forwarding path:
    Domains → [domain] → Domain Forwarding → Add/Edit Forwarding Rule

    Alternatively: Update nameservers to Cloudflare, then use Cloudflare Page Rules.
    The Cloudflare approach is recommended for bulk operations.
    """
    try:
        from playwright.sync_api import sync_playwright, TimeoutError as PWTimeout

        username = VENTRAIP_CONFIG["username"]
        password = VENTRAIP_CONFIG["password"]

        if not username or not password:
            log.error("VentraIP credentials not configured. Check VENTRAIP_CONFIG.")
            log.info(f"[VENTRAIP MANUAL] Set up: {domain} → 301 → {target_url}")
            log.info(f"  URL: {VENTRAIP_CONFIG['login_url']}")
            log.info(f"  Path: Domains → {domain} → Forwarding → Add rule")
            return False

        with sync_playwright() as p:
            browser = p.chromium.launch(headless=VENTRAIP_CONFIG["headless"])
            context = browser.new_context()
            page = context.new_page()

            # Login to VIPcontrol
            log.info(f"[VENTRAIP] Logging into VIPcontrol for {domain}...")
            page.goto(VENTRAIP_CONFIG["login_url"], wait_until="networkidle")

            # Fill login form
            page.fill("input[name='email'], input[type='email'], #email", username)
            page.fill("input[name='password'], input[type='password'], #password", password)
            page.click("button[type='submit'], input[type='submit'], .login-btn")
            page.wait_for_load_state("networkidle")

            # Check login success
            if "login" in page.url.lower():
                log.error(f"[VENTRAIP] Login failed — check credentials")
                browser.close()
                return False

            log.info(f"[VENTRAIP] Logged in. Navigating to domain {domain}...")

            # Navigate to domain management
            # VIPcontrol typically has a domain search or list
            page.goto(f"https://vip.ventraip.com.au/domains", wait_until="networkidle")

            # Search for domain
            try:
                page.fill("input[placeholder*='search'], input[name='search'], #domain-search", domain)
                page.press("input[placeholder*='search'], input[name='search']", "Enter")
                page.wait_for_load_state("networkidle")
            except Exception:
                pass  # Some versions use a list view without search

            # Click on the domain
            page.click(f"a:has-text('{domain}')", timeout=10000)
            page.wait_for_load_state("networkidle")

            # Navigate to forwarding section
            forwarding_link = page.locator("a:has-text('Forwarding'), a:has-text('URL Forwarding'), #forwarding-tab")
            if forwarding_link.count() > 0:
                forwarding_link.first.click()
                page.wait_for_load_state("networkidle")
            else:
                # Try direct URL
                domain_id = page.url.split("/")[-1]
                page.goto(f"https://vip.ventraip.com.au/domains/{domain_id}/forwarding")
                page.wait_for_load_state("networkidle")

            # Add or update forwarding rule
            add_btn = page.locator("button:has-text('Add'), a:has-text('Add Forwarding')")
            if add_btn.count() > 0:
                add_btn.first.click()
                page.wait_for_load_state("networkidle")

            # Fill forwarding target
            page.fill("input[name='destination'], input[name='target'], #forward-url", target_url)

            # Select redirect type (301 Permanent)
            redirect_type = page.locator("select[name='type'], #redirect-type")
            if redirect_type.count() > 0:
                redirect_type.select_option("301")

            # Save
            page.click("button[type='submit'], input[type='submit'], .save-btn")
            page.wait_for_load_state("networkidle")

            # Verify success
            success = page.locator(".success, .alert-success, [class*='success']").count() > 0
            if success:
                log.info(f"[VENTRAIP OK] {domain} → 301 → {target_url}")
            else:
                log.warning(f"[VENTRAIP UNCERTAIN] {domain} — verify manually at VIPcontrol")

            browser.close()
            return success

    except ImportError:
        log.error("Playwright not installed. Run: pip install playwright && playwright install chromium")
        log.info(f"[VENTRAIP MANUAL REQUIRED] {domain} → 301 → {target_url}")
        return False
    except Exception as e:
        log.error(f"[VENTRAIP ERROR] {domain}: {e}")
        return False


# ============================================================
# STRATEGY 3: Cloudflare Page Rules — best for bulk (RECOMMENDED)
# ============================================================

def set_cloudflare_redirect(domain: str, target_url: str, zone_id: Optional[str] = None) -> bool:
    """
    Set a 301 redirect using Cloudflare Page Rules.
    This is the RECOMMENDED approach for VentraIP domains:
    1. Update VentraIP nameservers to Cloudflare NS (one-time, manual per domain)
    2. Then manage all redirects via Cloudflare API (fully automated)

    Requires:
    - Domain already added to Cloudflare account
    - CLOUDFLARE_CONFIG["api_token"] set with Zone:Edit permissions
    """
    try:
        import requests

        api_token = CLOUDFLARE_CONFIG["api_token"]
        if not api_token:
            log.error("Cloudflare API token not configured. Check CLOUDFLARE_CONFIG.")
            return False

        headers = {
            "Authorization": f"Bearer {api_token}",
            "Content-Type": "application/json",
        }
        base = CLOUDFLARE_CONFIG["base_url"]

        # Find zone_id if not provided
        if not zone_id:
            resp = requests.get(
                f"{base}/zones?name={domain}",
                headers=headers,
                timeout=15
            )
            zones = resp.json().get("result", [])
            if not zones:
                log.error(f"[CLOUDFLARE] Zone not found for {domain}. Add domain to Cloudflare first.")
                return False
            zone_id = zones[0]["id"]

        # Delete any existing Page Rules for this domain (clean slate)
        existing = requests.get(f"{base}/zones/{zone_id}/pagerules", headers=headers, timeout=15)
        for rule in existing.json().get("result", []):
            rule_url = rule.get("targets", [{}])[0].get("constraint", {}).get("value", "")
            if domain in rule_url:
                requests.delete(f"{base}/zones/{zone_id}/pagerules/{rule['id']}", headers=headers)
                log.info(f"[CLOUDFLARE] Deleted existing Page Rule for {domain}")

        # Create 301 Page Rule: *domain.com/* → target_url
        page_rule = {
            "targets": [
                {
                    "target": "url",
                    "constraint": {
                        "operator": "matches",
                        "value": f"*{domain}/*",
                    }
                }
            ],
            "actions": [
                {
                    "id": "forwarding_url",
                    "value": {
                        "url": target_url,
                        "status_code": 301,
                    }
                }
            ],
            "status": "active",
            "priority": 1,
        }

        resp = requests.post(
            f"{base}/zones/{zone_id}/pagerules",
            json=page_rule,
            headers=headers,
            timeout=15
        )

        if resp.status_code in (200, 201):
            log.info(f"[CLOUDFLARE OK] {domain} → 301 → {target_url} (zone: {zone_id})")
            return True
        else:
            log.error(f"[CLOUDFLARE FAIL] {domain} HTTP {resp.status_code}: {resp.text}")
            return False

    except ImportError:
        log.error("requests library not installed. Run: pip install requests")
        return False
    except Exception as e:
        log.error(f"[CLOUDFLARE ERROR] {domain}: {e}")
        return False


# ============================================================
# STRATEGY 4: Namecheap API
# ============================================================

def set_namecheap_redirect(domain: str, target_url: str) -> bool:
    """
    Set URL redirect via Namecheap DNS hosting (host records update).
    Namecheap supports URL redirect type in host records (302/301).
    """
    try:
        import requests
        import xml.etree.ElementTree as ET

        cfg = NAMECHEAP_CONFIG
        if not cfg["api_key"]:
            log.error("Namecheap API key not configured.")
            return False

        # Split domain into SLD + TLD for Namecheap API
        parts = domain.rsplit(".", 2)
        if len(parts) == 3:
            sld, tld = parts[0], f"{parts[1]}.{parts[2]}"
        else:
            sld, tld = parts[0], parts[1]

        params = {
            "ApiUser": cfg["api_user"],
            "ApiKey": cfg["api_key"],
            "UserName": cfg["api_user"],
            "ClientIp": cfg["client_ip"],
            "Command": "namecheap.domains.dns.setHosts",
            "SLD": sld,
            "TLD": tld,
            "HostName1": "@",
            "RecordType1": "URL",
            "Address1": target_url,
            "TTL1": "1800",
            "HostName2": "www",
            "RecordType2": "URL",
            "Address2": target_url,
            "TTL2": "1800",
        }

        resp = requests.get(cfg["base_url"], params=params, timeout=15)
        root = ET.fromstring(resp.text)
        status = root.attrib.get("Status", "ERROR")

        if status == "OK":
            log.info(f"[NAMECHEAP OK] {domain} → 301 → {target_url}")
            return True
        else:
            errors = root.findall(".//Error")
            err_msg = "; ".join(e.text for e in errors if e.text) if errors else resp.text
            log.error(f"[NAMECHEAP FAIL] {domain}: {err_msg}")
            return False

    except ImportError:
        log.error("requests library not installed. Run: pip install requests")
        return False
    except Exception as e:
        log.error(f"[NAMECHEAP ERROR] {domain}: {e}")
        return False


# ============================================================
# MAIN ORCHESTRATOR
# ============================================================

REGISTRAR_HANDLERS = {
    "godaddy": set_godaddy_redirect,
    "ventraip": set_ventraip_redirect,
    "cloudflare": set_cloudflare_redirect,
    "namecheap": set_namecheap_redirect,
}

# Built-in redirect map — the canonical list for the Genesis domain empire
# Update target_url as products evolve
GENESIS_REDIRECT_MAP = [
    # ReceptionistAI — industry verticals (301 → receptionistai.au)
    {"domain": "voiceassistant.au",         "target_url": "https://receptionistai.au", "registrar": "ventraip"},
    {"domain": "voiceassistant.com.au",     "target_url": "https://receptionistai.au", "registrar": "ventraip"},
    {"domain": "aivoicereceptionist.au",    "target_url": "https://receptionistai.au", "registrar": "ventraip"},
    {"domain": "phonebot.au",               "target_url": "https://receptionistai.au", "registrar": "ventraip"},
    {"domain": "bookingbot.au",             "target_url": "https://receptionistai.au", "registrar": "ventraip"},
    {"domain": "talkbot.au",               "target_url": "https://receptionistai.au", "registrar": "ventraip"},
    {"domain": "legalbotai.au",            "target_url": "https://receptionistai.au", "registrar": "ventraip"},
    {"domain": "propertybotai.com.au",     "target_url": "https://receptionistai.au", "registrar": "ventraip"},
    {"domain": "electricianbotai.au",      "target_url": "https://receptionistai.au", "registrar": "ventraip"},
    {"domain": "aitradie.au",              "target_url": "https://receptionistai.au", "registrar": "ventraip"},
    # Tradie cluster consolidation
    {"domain": "tradiechatbot.com.au",     "target_url": "https://tradiechatbots.com.au", "registrar": "ventraip"},
    # Web design consolidation
    {"domain": "aiwebsitessydney.com.au",  "target_url": "https://aiwebdesignsydney.com.au", "registrar": "ventraip"},
    {"domain": "aiwebdesignsydney.au",     "target_url": "https://aiwebdesignsydney.com.au", "registrar": "ventraip"},
    {"domain": "aiwebsitessydney.au",      "target_url": "https://aiwebdesignsydney.com.au", "registrar": "ventraip"},
    {"domain": "aiwebdesignsydney.site",   "target_url": "https://aiwebdesignsydney.com.au", "registrar": "ventraip"},
    {"domain": "ecommercewebsites.site",   "target_url": "https://ecommercewebsites.au",     "registrar": "ventraip"},
    {"domain": "aichatbotsbrisbane.au",    "target_url": "https://brisbanechatbots.com.au",  "registrar": "ventraip"},
    # Brand consolidation
    {"domain": "sunaiva.com.au",           "target_url": "https://sunaiva.com",        "registrar": "godaddy"},
    {"domain": "sunaivasites.com.au",      "target_url": "https://sunaiva.com",        "registrar": "godaddy"},
    {"domain": "sunaivacore.com.au",       "target_url": "https://sunaiva.com",        "registrar": "godaddy"},
    {"domain": "sunaivaflow.com.au",       "target_url": "https://sunaiva.com",        "registrar": "godaddy"},
    {"domain": "agileadapt.site",          "target_url": "https://agileadapt.com.au",  "registrar": "ventraip"},
    {"domain": "aiagentic.au",             "target_url": "https://agileadapt.com.au",  "registrar": "ventraip"},
    # Voice widget consolidation
    {"domain": "talkingwidget.com",        "target_url": "https://talkingwidget.ai",   "registrar": "namecheap"},
    {"domain": "talkingwebsite.au",        "target_url": "https://talkingwebsite.com.au", "registrar": "ventraip"},
]


def process_redirects(records: list[dict], dry_run: bool = False) -> dict:
    """Process all redirect records. Returns summary of results."""
    results = {"success": [], "failed": [], "skipped": []}

    for i, rec in enumerate(records):
        domain = rec["domain"]
        target = rec["target_url"]
        registrar = rec["registrar"]

        log.info(f"[{i+1}/{len(records)}] {domain} → {target} via {registrar}")

        if dry_run:
            log.info(f"  [DRY RUN] Would set 301 redirect")
            results["success"].append(domain)
            continue

        handler = REGISTRAR_HANDLERS.get(registrar)
        if not handler:
            log.warning(f"  Unknown registrar '{registrar}' for {domain}. Skipping.")
            results["skipped"].append(domain)
            continue

        success = handler(domain, target)
        if success:
            results["success"].append(domain)
        else:
            results["failed"].append(domain)

        # Rate limiting between API calls
        time.sleep(1.0)

    return results


def print_summary(results: dict):
    """Print execution summary."""
    total = len(results["success"]) + len(results["failed"]) + len(results["skipped"])
    print("\n" + "=" * 70)
    print("BULK DOMAIN REDIRECT — EXECUTION SUMMARY")
    print("=" * 70)
    print(f"Total processed: {total}")
    print(f"Successful:      {len(results['success'])}")
    print(f"Failed:          {len(results['failed'])}")
    print(f"Skipped:         {len(results['skipped'])}")
    print()

    if results["success"]:
        print("SUCCESSFUL:")
        for d in results["success"]:
            print(f"  [OK] {d}")

    if results["failed"]:
        print("\nFAILED (manual action required):")
        for d in results["failed"]:
            print(f"  [FAIL] {d}")

    if results["skipped"]:
        print("\nSKIPPED:")
        for d in results["skipped"]:
            print(f"  [SKIP] {d}")

    print("\nLog saved to: E:/genesis-system/scripts/bulk_redirect_log.txt")
    print("=" * 70)


def generate_manual_instructions(records: list[dict]):
    """
    Generate manual VentraIP redirect instructions for when automation isn't available.
    Outputs a step-by-step guide for manual VIPcontrol updates.
    """
    ventraip_records = [r for r in records if r["registrar"] == "ventraip"]
    print("\n" + "=" * 70)
    print("MANUAL VENTRAIP REDIRECT INSTRUCTIONS")
    print("=" * 70)
    print(f"Login: https://vip.ventraip.com.au")
    print(f"Total domains to update: {len(ventraip_records)}")
    print()

    for i, rec in enumerate(ventraip_records, 1):
        print(f"{i:3}. {rec['domain']}")
        print(f"      Path: Domains → Manage → Forwarding → Add Rule")
        print(f"      Target: {rec['target_url']}")
        print(f"      Type: 301 (Permanent Redirect)")
        print()

    # Save to file
    output_path = "E:/genesis-system/scripts/ventraip_manual_redirects.txt"
    with open(output_path, "w") as f:
        f.write("VENTRAIP MANUAL REDIRECT INSTRUCTIONS\n")
        f.write(f"Generated: 2026-02-23\n")
        f.write(f"Total: {len(ventraip_records)} domains\n\n")
        for i, rec in enumerate(ventraip_records, 1):
            f.write(f"{i}. {rec['domain']}\n")
            f.write(f"   Target: {rec['target_url']}\n")
            f.write(f"   Type: 301 Permanent\n\n")

    print(f"Instructions saved to: {output_path}")


def generate_sample_csv():
    """Generate a sample CSV file from GENESIS_REDIRECT_MAP."""
    output_path = "E:/genesis-system/scripts/genesis_redirects.csv"
    with open(output_path, "w", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=["domain", "target_url", "registrar"])
        writer.writeheader()
        writer.writerows(GENESIS_REDIRECT_MAP)
    print(f"Sample CSV written to: {output_path}")
    print(f"Contains {len(GENESIS_REDIRECT_MAP)} redirect rules.")
    return output_path


def main():
    parser = argparse.ArgumentParser(
        description="Genesis Bulk Domain 301 Redirect Tool",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  # Run built-in Genesis redirect map
  python bulk_domain_redirect.py --genesis

  # Dry run (show what would happen, no changes)
  python bulk_domain_redirect.py --genesis --dry-run

  # Single domain redirect
  python bulk_domain_redirect.py --domain dentalbotai.au --target https://receptionistai.au --registrar ventraip

  # Process CSV file
  python bulk_domain_redirect.py --input genesis_redirects.csv

  # Generate sample CSV
  python bulk_domain_redirect.py --generate-csv

  # Generate manual VentraIP instructions (no automation required)
  python bulk_domain_redirect.py --genesis --manual
        """
    )

    parser.add_argument("--genesis", action="store_true", help="Run built-in Genesis redirect map")
    parser.add_argument("--input", help="CSV file with redirect instructions")
    parser.add_argument("--domain", help="Single domain to redirect")
    parser.add_argument("--target", help="Target URL for single domain redirect")
    parser.add_argument("--registrar", choices=list(REGISTRAR_HANDLERS.keys()), help="Registrar for single domain")
    parser.add_argument("--dry-run", action="store_true", help="Show what would happen without making changes")
    parser.add_argument("--manual", action="store_true", help="Generate manual instructions only (no automation)")
    parser.add_argument("--generate-csv", action="store_true", help="Generate sample CSV from built-in map")

    args = parser.parse_args()

    load_credentials()

    if args.generate_csv:
        generate_sample_csv()
        return

    records = []

    if args.genesis:
        records = GENESIS_REDIRECT_MAP
        log.info(f"Using built-in Genesis redirect map: {len(records)} domains")

    elif args.input:
        records = load_csv(args.input)

    elif args.domain and args.target and args.registrar:
        records = [{"domain": args.domain, "target_url": args.target, "registrar": args.registrar}]

    else:
        parser.print_help()
        print("\nQuick start: python bulk_domain_redirect.py --genesis --dry-run")
        sys.exit(1)

    if args.manual:
        generate_manual_instructions(records)
        return

    print(f"\nGenesis Bulk Domain Redirect")
    print(f"Domains to process: {len(records)}")
    print(f"Mode: {'DRY RUN' if args.dry_run else 'LIVE'}")
    print()

    results = process_redirects(records, dry_run=args.dry_run)
    print_summary(results)

    # Exit with error code if any failures
    sys.exit(1 if results["failed"] else 0)


if __name__ == "__main__":
    main()
