#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
FreeExile Marketing Hub Manager & Pipeline Auditor
Autonomous CLI tool for managing campaigns, auditing 9-language parity,
and monitoring marketing KPIs across channels.
"""

from __future__ import annotations

import argparse
import json
import os
import sys
from dataclasses import dataclass, field
from pathlib import Path
from typing import Dict, List, Optional, Tuple


@dataclass(slots=True, frozen=True)
class MarketingChecklist:
    """Checklist item definition."""
    name: str
    target_path: str
    required_keywords: Tuple[str, ...]
    min_lines: int


REQUIRED_LANGUAGES: Tuple[str, ...] = (
    "en", "vi", "zh", "ja", "ko", "th", "de", "ru", "es"
)

CORE_MARKETING_FILES: Tuple[MarketingChecklist, ...] = (
    MarketingChecklist(
        name="Marketing Overview",
        target_path="marketing/README.md",
        required_keywords=("FREEEXILE", "MARKETING", "GROWTH"),
        min_lines=30,
    ),
    MarketingChecklist(
        name="Agent Roster",
        target_path="marketing/ROSTER.md",
        required_keywords=("marketing_lead", "viral_content_creator", "arpg_outreach_scout"),
        min_lines=30,
    ),
    MarketingChecklist(
        name="Global Strategy",
        target_path="marketing/STRATEGY.md",
        required_keywords=("ROADMAP", "Wishlist", "Steam"),
        min_lines=40,
    ),
    MarketingChecklist(
        name="Steam & Storefront",
        target_path="marketing/channels/steam_and_storefront.md",
        required_keywords=("Steam", "Capsule", "ASO"),
        min_lines=30,
    ),
    MarketingChecklist(
        name="Short-form & Social",
        target_path="marketing/channels/shortform_and_social.md",
        required_keywords=("TikTok", "Shorts", "Viral"),
        min_lines=30,
    ),
    MarketingChecklist(
        name="Influencer Outreach",
        target_path="marketing/channels/influencer_outreach.md",
        required_keywords=("Streamer", "Creator", "Tier"),
        min_lines=30,
    ),
    MarketingChecklist(
        name="Community & Reddit",
        target_path="marketing/channels/community_and_reddit.md",
        required_keywords=("Discord", "Reddit", "Devlog"),
        min_lines=30,
    ),
    MarketingChecklist(
        name="Press & Media",
        target_path="marketing/channels/press_and_media.md",
        required_keywords=("Press Kit", "Release", "PC Gamer"),
        min_lines=30,
    ),
    MarketingChecklist(
        name="Campaign 01 - Manifesto",
        target_path="marketing/campaigns/01_the_savage_manifesto.md",
        required_keywords=("Manifesto", "P2W", "Barter"),
        min_lines=25,
    ),
    MarketingChecklist(
        name="Campaign 02 - 1500 Nodes",
        target_path="marketing/campaigns/02_flesh_bone_viral_tree.md",
        required_keywords=("1,500", "Flesh", "Bone"),
        min_lines=25,
    ),
    MarketingChecklist(
        name="Campaign 03 - Web Demo",
        target_path="marketing/campaigns/03_instant_zero_install.md",
        required_keywords=("Browser", "Demo", "Instant"),
        min_lines=25,
    ),
    MarketingChecklist(
        name="I18N Marketing Guide",
        target_path="marketing/localization/MARKETING_I18N_GUIDE.md",
        required_keywords=("9", "Locales", "Nuances"),
        min_lines=30,
    ),
    MarketingChecklist(
        name="Store Pitch 9 Languages",
        target_path="marketing/localization/store_pitch_9languages.md",
        required_keywords=("ENGLISH", "VIỆT", "中文", "日本語", "한국어"),
        min_lines=40,
    ),
)


class MarketingHubManager:
    """Manager class for inspecting and validating marketing infrastructure."""

    def __init__(self, root_dir: Optional[Path] = None) -> None:
        if root_dir is None:
            self.root_dir = Path(__file__).resolve().parents[2]
        else:
            self.root_dir = Path(root_dir)

    def audit_documents(self) -> Dict[str, object]:
        """Audit all marketing documents for existence, length and keywords."""
        results: List[Dict[str, object]] = []
        all_passed = True

        for item in CORE_MARKETING_FILES:
            file_path = self.root_dir / item.target_path
            status = "PASS"
            errors: List[str] = []

            if not file_path.exists():
                status = "FAIL"
                errors.append("File not found on disk")
                all_passed = False
                results.append({
                    "name": item.name,
                    "path": item.target_path,
                    "status": status,
                    "errors": errors,
                    "line_count": 0,
                })
                continue

            try:
                content = file_path.read_text(encoding="utf-8")
                lines = content.splitlines()
                line_count = len(lines)

                if line_count < item.min_lines:
                    status = "FAIL"
                    errors.append(f"Line count too short ({line_count} < {item.min_lines})")
                    all_passed = False

                for kw in item.required_keywords:
                    if kw.lower() not in content.lower():
                        status = "FAIL"
                        errors.append(f"Missing required keyword: '{kw}'")
                        all_passed = False

                results.append({
                    "name": item.name,
                    "path": item.target_path,
                    "status": status,
                    "errors": errors,
                    "line_count": line_count,
                })
            except Exception as exc:
                all_passed = False
                results.append({
                    "name": item.name,
                    "path": item.target_path,
                    "status": "FAIL",
                    "errors": [f"Read error: {exc}"],
                    "line_count": 0,
                })

        return {
            "all_passed": all_passed,
            "total_items": len(CORE_MARKETING_FILES),
            "passed_items": sum(1 for r in results if r["status"] == "PASS"),
            "details": results,
        }

    def verify_localization_parity(self) -> Dict[str, object]:
        """Verify that all 9 languages are fully represented in store pitches."""
        store_path = self.root_dir / "marketing/localization/store_pitch_9languages.md"
        missing_langs: List[str] = []

        if not store_path.exists():
            return {
                "success": False,
                "error": "store_pitch_9languages.md does not exist",
                "missing_languages": list(REQUIRED_LANGUAGES),
            }

        content = store_path.read_text(encoding="utf-8").lower()
        for lang in REQUIRED_LANGUAGES:
            tag = f"`{lang}`"
            if tag not in content and lang not in content:
                missing_langs.append(lang)

        return {
            "success": len(missing_langs) == 0,
            "required_languages": list(REQUIRED_LANGUAGES),
            "missing_languages": missing_langs,
            "languages_found": len(REQUIRED_LANGUAGES) - len(missing_langs),
        }

    def print_dashboard(self) -> int:
        """Render a clean terminal dashboard of marketing readiness."""
        print("=" * 72)
        print("  FREEEXILE AUTONOMOUS MARKETING STUDIO DASHBOARD")
        print("=" * 72)

        audit_res = self.audit_documents()
        loc_res = self.verify_localization_parity()

        print(f"[*] Total Core Marketing Documents: {audit_res['total_items']}")
        print(f"[*] Documents Passing Audit:       {audit_res['passed_items']} / {audit_res['total_items']}")
        print(f"[*] 9-Language Parity Coverage:    {loc_res['languages_found']} / {len(REQUIRED_LANGUAGES)}")

        print("-" * 72)
        print(f"{'Document Name':<30} | {'Status':<6} | {'Lines':<6} | Notes")
        print("-" * 72)
        for item in audit_res["details"]: # type: ignore
            err_str = ", ".join(item["errors"]) if item["errors"] else "OK"
            print(f"{item['name']:<30} | {item['status']:<6} | {item['line_count']:<6} | {err_str}")

        print("=" * 72)
        if audit_res["all_passed"] and loc_res["success"]:
            print(">>> STATUS: MARKETING PIPELINE IS 100% OPERATIONAL & DEPLOYABLE! <<<")
            return 0
        else:
            print(">>> STATUS: MARKETING AUDIT FOUND ISSUES REQUIRING ATTENTION. <<<")
            return 1


def main() -> None:
    """CLI entrypoint."""
    parser = argparse.ArgumentParser(description="FreeExile Marketing Hub Manager")
    parser.add_argument("--json", action="store_true", help="Output results in JSON format")
    parser.add_argument("--check-only", action="store_true", help="Run audit and return exit code")
    args = parser.parse_args()

    manager = MarketingHubManager()
    if args.json:
        doc_audit = manager.audit_documents()
        loc_audit = manager.verify_localization_parity()
        payload = {
            "documents": doc_audit,
            "localization": loc_audit,
            "status": "OPERATIONAL" if (doc_audit["all_passed"] and loc_audit["success"]) else "FAILED",
        }
        print(json.dumps(payload, indent=2, ensure_ascii=True))
        sys.exit(0 if payload["status"] == "OPERATIONAL" else 1)

    code = manager.print_dashboard()
    sys.exit(code)


if __name__ == "__main__":
    main()
