import os
import re
from pathlib import Path
from typing import Dict, List, Optional, Tuple

from docx import Document
from docx.shared import Pt


ROOT = Path(r"C:\Users\linux\OneDrive\Documents\CTO\Event-Org")
BACKEND_SRC = ROOT / "backend" / "src"
FRONTEND_SRC = ROOT / "frontend" / "src"


HTTP_DECORATORS = ("Get", "Post", "Put", "Patch", "Delete")


def read_text(path: Path) -> str:
    try:
        return path.read_text(encoding="utf-8")
    except UnicodeDecodeError:
        return path.read_text(encoding="utf-8", errors="replace")


def extract_backend_endpoints() -> List[Dict[str, str]]:
    """
    Returns a list of endpoint dicts:
    { module, file, controller_base, method, route, handler, guards_roles }
    """
    endpoints: List[Dict[str, str]] = []

    controller_files = sorted(BACKEND_SRC.rglob("*.controller.ts"))
    for f in controller_files:
        txt = read_text(f)

        m = re.search(r"@Controller\(\s*['\"]([^'\"]+)['\"]\s*\)", txt)
        base = m.group(1) if m else ""

        # Attempt to capture role guards usage broadly (best-effort).
        class_roles = []
        for rm in re.finditer(r"@Roles\(\s*([^)]+)\s*\)", txt):
            class_roles.append(rm.group(1).strip())
        class_roles_s = "; ".join(sorted(set(class_roles))) if class_roles else ""

        # Find methods with decorators. We do a simplified parse: look for decorator then method signature.
        for dec in HTTP_DECORATORS:
            # Example: @Post('login')
            for dm in re.finditer(rf"@{dec}\(\s*(['\"]([^'\"]*)['\"])?\s*\)", txt):
                route = dm.group(2) if dm.group(2) is not None else ""

                # Find next method name after decorator
                after = txt[dm.end() : dm.end() + 400]
                hm = re.search(r"\n\s*(async\s+)?([a-zA-Z0-9_]+)\s*\(", after)
                handler = hm.group(2) if hm else "(unknown)"

                endpoints.append(
                    {
                        "module": f.relative_to(BACKEND_SRC).parts[0] if f.relative_to(BACKEND_SRC).parts else "backend",
                        "file": str(f.relative_to(ROOT)),
                        "controller_base": base,
                        "method": dec.upper(),
                        "route": route,
                        "handler": handler,
                        "guards_roles": class_roles_s,
                    }
                )

        # Handle decorators with no parentheses: @Get() is already captured; but also support @Get without args via @Get()
        for dec in HTTP_DECORATORS:
            for dm in re.finditer(rf"@{dec}\(\s*\)", txt):
                after = txt[dm.end() : dm.end() + 400]
                hm = re.search(r"\n\s*(async\s+)?([a-zA-Z0-9_]+)\s*\(", after)
                handler = hm.group(2) if hm else "(unknown)"
                endpoints.append(
                    {
                        "module": f.relative_to(BACKEND_SRC).parts[0] if f.relative_to(BACKEND_SRC).parts else "backend",
                        "file": str(f.relative_to(ROOT)),
                        "controller_base": base,
                        "method": dec.upper(),
                        "route": "",
                        "handler": handler,
                        "guards_roles": class_roles_s,
                    }
                )

    # De-dup identical rows that can happen due to overlapping regex matches.
    seen = set()
    deduped = []
    for e in endpoints:
        key = (e["file"], e["controller_base"], e["method"], e["route"], e["handler"])
        if key in seen:
            continue
        seen.add(key)
        deduped.append(e)
    return deduped


def extract_frontend_routes(app_tsx: Path) -> List[Dict[str, str]]:
    txt = read_text(app_tsx)
    routes: List[Dict[str, str]] = []

    # Basic extraction of <Route path="..." element={<Component />}
    for m in re.finditer(r"<Route\s+path=['\"]([^'\"]+)['\"][^>]*element=\{<([^>\s/]+)", txt):
        routes.append({"path": m.group(1), "element": m.group(2)})

    # Nested routes like <Route path="/dashboard" element={<AuthGuard><Layout /></AuthGuard>}>
    # Capture those too (element name might be AuthGuard wrapper, so keep a raw snippet)
    for m in re.finditer(r"<Route\s+path=['\"]([^'\"]+)['\"][^>]*element=\{([^}]+)\}", txt):
        snippet = re.sub(r"\s+", " ", m.group(2)).strip()
        routes.append({"path": m.group(1), "element": snippet})

    # De-dup by path+element
    seen = set()
    out = []
    for r in routes:
        key = (r["path"], r["element"])
        if key in seen:
            continue
        seen.add(key)
        out.append(r)
    return out


def add_heading(doc: Document, text: str, level: int) -> None:
    doc.add_heading(text, level=level)


def add_kv_table(doc: Document, rows: List[Tuple[str, str]]) -> None:
    table = doc.add_table(rows=1, cols=2)
    hdr = table.rows[0].cells
    hdr[0].text = "Item"
    hdr[1].text = "Details"
    for k, v in rows:
        cells = table.add_row().cells
        cells[0].text = k
        cells[1].text = v


def main() -> None:
    doc = Document()

    # Global styling (light touch)
    style = doc.styles["Normal"]
    style.font.name = "Calibri"
    style.font.size = Pt(11)

    add_heading(doc, "CampaignHub — Client-Facing Product Guide & User Flows", 0)
    doc.add_paragraph(
        "This document explains CampaignHub in plain language: what the platform is for, what features are included, "
        "and how each type of user moves from signup to day-to-day operations and payments."
    )

    add_heading(doc, "1. Product Summary (What CampaignHub Is)", 1)
    doc.add_paragraph(
        "CampaignHub is an end-to-end collaboration platform designed to help Brands and Creators work together in a structured, trackable, and safe way. "
        "It brings campaign discovery, creator selection, contracts, task-based delivery tracking, messaging, and payments into one workflow."
    )

    add_heading(doc, "2. Who It’s For (Personas)", 1)
    add_kv_table(
        doc,
        [
            ("Brands", "Marketing teams that want to launch creator campaigns, find the right talent faster, track deliverables, and pay creators with a clear audit trail."),
            ("Creators", "Influencers and studios who want consistent deal flow, clear requirements, simple submission, and reliable payments."),
            ("Talent Managers", "Agencies/managers coordinating multiple creators, keeping work organized across campaigns and deliverables."),
            ("Platform Admins", "Operations teams responsible for verification, safety, platform settings, dispute/support handling, and system oversight."),
        ],
    )

    add_heading(doc, "3. Why It’s Different (Next-Gen AI + Operational Controls)", 1)
    doc.add_paragraph(
        "CampaignHub is built around two ideas: (1) simplify collaboration into clear steps (invite/apply → contract → tasks → submission → review → payment), "
        "and (2) use AI to reduce manual research and improve decision quality for both brands and creators."
    )

    add_heading(doc, "4. Feature Tour (What’s Included)", 1)
    add_heading(doc, "4.1 Next-Gen AI Features", 2)
    doc.add_paragraph(
        "CampaignHub includes an AI Hub designed to assist with matching, evaluation, and performance insights. "
        "These tools help brands choose creators faster and help creators present better pitches and content."
    )
    add_kv_table(
        doc,
        [
            ("Smart Matching", "Recommends creators for a campaign based on fit (niche, platform, engagement, and profile signals)."),
            ("Applicant Ranking", "Automatically sorts applicants using predictive signals, so brands can review the best candidates first."),
            ("Performance Prediction", "Estimates expected reach/engagement and ROI-like outcomes to support planning and budgeting."),
            ("AI Content Generator", "Helps generate captions/brief text and creator pitch text to speed up campaign prep and negotiation."),
            ("Deep Research & Metric Scanning", "Supports analysis of submitted social links and can generate an AI review summary for submitted deliverables."),
            ("Executive Summaries", "Summarizes team progress and outstanding tasks to support managers/brands."),
        ],
    )

    add_heading(doc, "4.2 Collaboration Features (Core Platform)", 2)
    add_kv_table(
        doc,
        [
            ("Campaigns & Discovery", "Brands can post campaigns; creators can browse and apply."),
            ("Marketplace Offers", "Creators/managers publish packaged services (price, deliverables type, delivery time). Brands can browse and invite directly."),
            ("Contracts", "Defines collaboration terms and ties work to tasks and delivery tracking."),
            ("Workspace (Tasks & Deliverables)", "Brands assign tasks; creators submit proof via links; status-based review and approvals keep work transparent."),
            ("Messaging", "Direct chat between users to coordinate and negotiate."),
            ("Notifications (Web + Telegram)", "Operational updates can be delivered in-app and via Telegram once connected."),
            ("Payments & Transaction History", "Brands initiate payments; both parties track statuses and history."),
            ("Payout Account Setup", "Creators/managers set bank details and can verify account readiness for payouts."),
            ("Admin Operations", "User verification (KYC), roles, platform settings/maintenance mode, support handling."),
        ],
    )

    add_heading(doc, "5. End-to-End User Flow (From Signup to Payment)", 1)
    doc.add_paragraph("The lifecycle is intentionally simple and repeatable:")
    doc.add_paragraph("Step 1 — Sign up and verify identity (KYC).")
    doc.add_paragraph("Step 2 — Get approved (admin verification).")
    doc.add_paragraph("Step 3 — Find work (apply to campaigns or receive an invitation / offer booking).")
    doc.add_paragraph("Step 4 — Agree terms (contract).")
    doc.add_paragraph("Step 5 — Execute work (tasks in Workspace).")
    doc.add_paragraph("Step 6 — Submit deliverables (post links / proof).")
    doc.add_paragraph("Step 7 — Review and approve (brand/admin).")
    doc.add_paragraph("Step 8 — Pay and track transactions (payments page + payout account readiness).")

    add_heading(doc, "6. Step-by-Step Guides (By Role)", 1)

    add_heading(doc, "6.1 Creator Guide (How Creators Use the Platform)", 2)
    doc.add_paragraph("A creator’s experience focuses on visibility, clarity of requirements, simple submission, and payment reliability.")
    add_heading(doc, "6.1.1 Sign Up & Verification", 3)
    doc.add_paragraph("1) Choose role: Creator.")
    doc.add_paragraph("2) Create credentials (email + password).")
    doc.add_paragraph("3) Upload ID (front/back) and complete live video verification.")
    doc.add_paragraph("4) Connect Telegram for status updates.")
    add_heading(doc, "6.1.2 Get Work", 3)
    doc.add_paragraph("Option A — Apply to Campaigns: open Public Campaigns → choose a campaign → apply.")
    doc.add_paragraph("Option B — Receive Invitation: brands can invite you from Marketplace Offers or team workflows.")
    add_heading(doc, "6.1.3 Deliver & Get Paid", 3)
    doc.add_paragraph("1) Open Workspace to view assigned tasks.")
    doc.add_paragraph("2) For each task: start → complete → paste your post link as proof.")
    doc.add_paragraph("3) Optional: AI review can be generated for submitted links to help brands evaluate performance.")
    doc.add_paragraph("4) Set up your payout/bank details (Payout Settings).")
    doc.add_paragraph("5) Track payment status in Payments → Transaction History.")

    add_heading(doc, "6.2 Brand Guide (How Brands Run Campaigns)", 2)
    doc.add_paragraph("Brands use CampaignHub to reduce creator sourcing time, keep deliverables on schedule, and keep payments auditable.")
    add_heading(doc, "6.2.1 Sign Up & Verification", 3)
    doc.add_paragraph("1) Choose role: Brand.")
    doc.add_paragraph("2) Upload required identity verification (KYC).")
    doc.add_paragraph("3) Complete brand profile (company and contact details).")
    add_heading(doc, "6.2.2 Launch a Campaign", 3)
    doc.add_paragraph("1) Create a campaign and define deliverables, platforms, budget, and requirements.")
    doc.add_paragraph("2) Review applications and shortlist creators.")
    doc.add_paragraph("3) Use AI tools (matching/ranking/prediction) to speed up selection and reduce research effort.")
    add_heading(doc, "6.2.3 Manage Deliverables (Workspace)", 3)
    doc.add_paragraph("1) Create/approve a contract.")
    doc.add_paragraph("2) Assign tasks to talent (with optional due dates).")
    doc.add_paragraph("3) Review completed tasks and approve or request changes.")
    add_heading(doc, "6.2.4 Pay Talent (Payments)", 3)
    doc.add_paragraph("1) Open Payments → Instant Pay.")
    doc.add_paragraph("2) Select payee, amount, and method.")
    doc.add_paragraph("3) Complete provider checkout; track status in Transaction History.")
    doc.add_paragraph("4) Bank readiness indicators help ensure recipients have payout details configured.")

    add_heading(doc, "6.3 Manager Guide (How Managers Coordinate Teams)", 2)
    doc.add_paragraph("Managers use CampaignHub to organize multiple creators and keep execution visible across many deliverables.")
    doc.add_paragraph("1) Build your team using My Team + Invitations.")
    doc.add_paragraph("2) Coordinate deals in Messages.")
    doc.add_paragraph("3) Track tasks and submission links in Workspace.")
    doc.add_paragraph("4) Publish Offers to standardize service pricing and speed up booking.")

    add_heading(doc, "6.4 Admin Guide (How the Platform Is Operated)", 2)
    doc.add_paragraph("Admins keep the ecosystem safe, verified, and consistent.")
    doc.add_paragraph("1) Review pending verification accounts and approve/deny.")
    doc.add_paragraph("2) Manage users, roles, and permissions.")
    doc.add_paragraph("3) Monitor campaigns, applications, contracts, and payouts/transactions.")
    doc.add_paragraph("4) Manage platform settings including maintenance mode and public-facing text.")
    doc.add_paragraph("5) Handle support tickets and operational issues.")

    add_heading(doc, "7. Payments & Payouts Explained (Client-Friendly)", 1)
    doc.add_paragraph(
        "CampaignHub provides payment initiation and transaction tracking so brands can pay talent and both sides can see what happened and when. "
        "Creators/managers configure payout/bank details so funds can be routed correctly."
    )
    add_kv_table(
        doc,
        [
            ("Instant Pay", "Brands can send payments to talent by selecting a recipient and completing checkout."),
            ("Transaction statuses", "Transactions move through states like initiated → processing → completed (or failed)."),
            ("Bank/Payout setup", "Talent can save and verify bank details; brands can see if a recipient is payout-ready."),
            ("Audit trail", "Payment history provides timestamps and parties for accountability and reconciliation."),
        ],
    )

    add_heading(doc, "8. What Screens the Client Gets (UI Overview)", 1)
    doc.add_paragraph("Below is a high-level list of the main screens available in the platform (names may appear in navigation as shown).")
    add_kv_table(
        doc,
        [
            ("Public Pages", "Landing, Public Campaigns, Public Creators, Public Managers, Talent Network."),
            ("Auth", "Login, Register (KYC + Telegram connection)."),
            ("Core", "Dashboard, Messages, Workspace, Contracts, Offers, Invitations, Payments, Analytics, AI Hub."),
            ("Creator", "Creator Dashboard, Creator Profile, Creator Applications."),
            ("Brand", "Brand Dashboard, Brand Profile, Brand Campaigns, Brand Applications."),
            ("Manager", "Manager Dashboard, My Team, Workspace."),
            ("Admin", "Admin Dashboard, Users, Roles, Campaigns, Applications, Payouts, Site Settings, Support, Telegram Studio."),
        ],
    )

    add_heading(doc, "9. Glossary (Simple Definitions)", 1)
    add_kv_table(
        doc,
        [
            ("Campaign", "A brand’s opportunity describing what content is needed and what success looks like."),
            ("Application", "A creator’s request to participate in a campaign."),
            ("Offer (Marketplace)", "A packaged service a creator/manager sells (price + delivery time + content type)."),
            ("Invitation", "A direct request to collaborate or book an offer."),
            ("Contract", "The agreement that formalizes the collaboration and ties work to delivery tracking."),
            ("Workspace / Task", "Where deliverables are assigned, tracked, and approved."),
            ("Payout Account", "Bank details used to pay talent."),
            ("Transaction", "A record of a payment attempt and its status."),
        ],
    )

    add_heading(doc, "10. Technical Appendix (Optional)", 1)
    doc.add_paragraph("This appendix is only for technical stakeholders (hosting/operations).")
    doc.add_paragraph("Backend exposes APIs under /api. Frontend is the web UI. Optional AI engine can run separately and power AI Hub features.")

    out_path = ROOT / "CampaignHub_Client_Product_Guide_and_User_Flows.docx"
    doc.save(out_path)
    print(f"Wrote: {out_path}")


if __name__ == "__main__":
    main()

