#!/usr/bin/env python3
"""Generate 53 framework .mdx doc pages from profiles/framework_registry.yaml."""

import os
import sys

import yaml

YAML_PATH = os.path.join(os.path.dirname(__file__), "..", "profiles", "framework_registry.yaml")
OUTPUT_DIR = os.path.join(os.path.dirname(__file__), "..", "docs", "src", "content", "docs", "frameworks")

TIER_VARIANT = {
    "community": "success",
    "pro": "note",
    "team": "caution",
    "agency": "danger",
    "enterprise": "danger",
    "enterprise_unlimited": "danger",
}

TIER_REMEDIATION = {
    "community": "Remediation is included free at all tiers.",
    "pro": "Requires Pro tier or higher ($599/yr) for remediation.",
    "team": "Requires Team tier or higher ($1,999/yr) for remediation.",
    "agency": "Requires Agency tier or higher ($4,999/yr) for remediation.",
    "enterprise": "Requires Enterprise tier ($24,999/yr) for remediation.",
    "enterprise_unlimited": "Requires Enterprise Unlimited tier (custom pricing) for remediation.",
}

# Community framework IDs for global related-frameworks fallback
COMMUNITY_IDS = {"soc2", "cis_gcp", "cis_azure", "cis_aws"}


def build_region_lookup(regions):
    """Map region id → region name."""
    return {r["id"]: r["name"] for r in regions}


def format_countries(countries):
    if not countries:
        return "Worldwide"
    if len(countries) == 27:
        return "All 27 EU member states"
    return ", ".join(countries)


def build_related(framework, all_frameworks):
    """List other frameworks in the same region. For global, list other community frameworks."""
    fid = framework["id"]
    region = framework["jurisdiction"]["region"]

    if region == "global":
        related = [fw for fw in all_frameworks if fw["id"] in COMMUNITY_IDS and fw["id"] != fid]
    else:
        related = [
            fw
            for fw in all_frameworks
            if fw["jurisdiction"]["region"] == region and fw["id"] != fid
        ]

    if not related:
        return "No related frameworks in this region."

    lines = [f'- [{fw["name"]}](/frameworks/{fw["id"]})' for fw in related]
    return "\n".join(lines)


def generate_page(fw, all_frameworks, region_lookup):
    tier = fw["tier"]
    jur = fw["jurisdiction"]
    category_display = fw["category"].replace("_", " ").title()
    tier_display = tier.replace("_", " ").title()
    scope_display = jur["scope"].capitalize()
    region_display = region_lookup.get(jur["region"], jur["region"])
    countries_display = format_countries(jur.get("countries", []))
    coverage_notes = fw.get("coverage_notes")
    coverage_notes_line = f'\n**Coverage notes:** {coverage_notes}' if coverage_notes else ""

    related_section = build_related(fw, all_frameworks)

    return f'''---
title: "{fw["name"]}"
description: "Terraform compliance scanning for {fw["name"]} — assess for free, remediate with ComplyForm"
---

import {{ Badge }} from '@astrojs/starlight/components';

<Badge text="{tier_display}" variant="{TIER_VARIANT[tier]}" />
<Badge text="{category_display}" variant="tip" />

**Issuing body:** [{jur["issuing_body"]}]({jur["issuing_body_url"]})
**Jurisdiction:** {scope_display} — {region_display}
**Countries:** {countries_display}
{coverage_notes_line}

## Assessment

Assess your infrastructure against {fw["short_name"]} for free at any tier:

```bash
complyform assess --frameworks={fw["id"]}
```

## Remediation

{TIER_REMEDIATION[tier]}

```bash
complyform remediate --frameworks={fw["id"]}
```

## Related Frameworks

{related_section}
'''


def main():
    yaml_path = os.path.normpath(YAML_PATH)
    if not os.path.isfile(yaml_path):
        print(f"Error: {yaml_path} not found", file=sys.stderr)
        sys.exit(1)

    try:
        with open(yaml_path, "r") as f:
            data = yaml.safe_load(f)
    except yaml.YAMLError as e:
        print(f"Error parsing YAML: {e}", file=sys.stderr)
        sys.exit(1)

    regions = data.get("regions", [])
    frameworks = data.get("frameworks", [])
    region_lookup = build_region_lookup(regions)

    output_dir = os.path.normpath(OUTPUT_DIR)
    os.makedirs(output_dir, exist_ok=True)

    count = 0
    for fw in frameworks:
        fid = fw["id"]
        page_content = generate_page(fw, frameworks, region_lookup)
        output_path = os.path.join(output_dir, f"{fid}.mdx")
        with open(output_path, "w") as f:
            f.write(page_content)
        count += 1

    print(f"Generated {count} framework pages in docs/src/content/docs/frameworks/")


if __name__ == "__main__":
    main()
