from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
PRESET_FILE = ROOT / "Config" / "AgrarianRenderingPresets.ini"
DOCS_FILE = ROOT / "Docs" / "Rendering" / "InvestorRenderingPresets.md"
ROADMAP_FILE = ROOT / "AGRARIAN_DEVELOPMENT_ROADMAP.md"

EXPECTED_PRESETS = {
    "AgrarianRenderingPreset.Default": {
        "RayTracing": "Disabled",
        "TargetResolution": "1920x1080",
        "TargetFrameRate": "60",
        "required_cvars": {
            "r.RayTracing=0",
            "r.Lumen.HardwareRayTracing=0",
            "r.PathTracing=0",
        },
    },
    "AgrarianRenderingPreset.Recommended": {
        "RayTracing": "Disabled",
        "TargetResolution": "2560x1440",
        "TargetFrameRate": "60",
        "required_cvars": {
            "r.RayTracing=0",
            "r.Lumen.HardwareRayTracing=0",
            "r.PathTracing=0",
        },
    },
    "AgrarianRenderingPreset.Cinematic": {
        "RayTracing": "Optional",
        "TargetResolution": "3840x2160",
        "TargetFrameRate": "30",
        "required_cvars": {
            "r.RayTracing=1",
            "r.Lumen.HardwareRayTracing=1",
            "r.PathTracing=0",
        },
    },
}


def read_presets():
    presets = {}
    active_section = None
    for raw_line in PRESET_FILE.read_text(encoding="utf-8").splitlines():
        line = raw_line.strip()
        if not line or line.startswith(";"):
            continue
        if line.startswith("[") and line.endswith("]"):
            active_section = line[1:-1]
            presets[active_section] = {"CVars": []}
            continue
        if not active_section or "=" not in line:
            continue

        key, value = line.split("=", 1)
        if key == "+CVars":
            presets[active_section]["CVars"].append(value)
        else:
            presets[active_section][key] = value
    return presets


def main():
    failures = []
    if not PRESET_FILE.exists():
        failures.append(f"missing {PRESET_FILE}")
    if not DOCS_FILE.exists():
        failures.append(f"missing {DOCS_FILE}")
    if failures:
        raise SystemExit("Investor rendering preset verification failed:\n" + "\n".join(failures))

    parser = read_presets()
    for preset_name, expectations in EXPECTED_PRESETS.items():
        if preset_name not in parser:
            failures.append(f"missing preset section {preset_name}")
            continue

        section = parser[preset_name]
        for key, expected_value in expectations.items():
            if key == "required_cvars":
                continue
            actual_value = section.get(key)
            if actual_value != expected_value:
                failures.append(f"{preset_name} {key} expected {expected_value}, got {actual_value}")

        cvars = set(section.get("CVars", []))
        missing_cvars = sorted(expectations["required_cvars"] - cvars)
        if missing_cvars:
            failures.append(f"{preset_name} missing CVars: {', '.join(missing_cvars)}")

    docs_text = DOCS_FILE.read_text(encoding="utf-8")
    for snippet in [
        "Default",
        "Recommended",
        "Cinematic",
        "No gameplay feature should require ray tracing.",
        "default investor demo must remain credible with ray tracing disabled",
    ]:
        if snippet not in docs_text:
            failures.append(f"{DOCS_FILE} missing snippet: {snippet}")

    roadmap_text = ROADMAP_FILE.read_text(encoding="utf-8")
    if "[x] Define default, recommended, and cinematic investor rendering presets" not in roadmap_text:
        failures.append("roadmap item is not marked complete")

    if failures:
        raise SystemExit("Investor rendering preset verification failed:\n" + "\n".join(failures))

    print("PASS: investor rendering presets define non-ray-traced default/recommended and optional cinematic ray tracing.")


if __name__ == "__main__":
    main()
