#!/usr/bin/env python3
"""script/gate_presentation.py -- Presentation standard compliance gate.

Checks:
1. README.md exists and contains required markers (privacy sentence + Tier line)
2. CHANGELOG.md exists and mentions the current version
3. VERSION file (if present) has no leading 'v'

Exit 0 on success, 1 on any violation.
"""

import re
import sys
from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parent.parent

PRIVACY_SENTENCE = (
    "All AbilityBI GitHub repos are PRIVATE by default. No repository is made "
    "public, published to a public package registry, or released externally "
    "unless the owner explicitly instructs otherwise."
)

TIER_PATTERN = re.compile(r"Tier:\s*Tier-[123]")


def _read_text(path: Path) -> str:
    """Read file as UTF-8, return empty string if missing."""
    try:
        return path.read_text(encoding="utf-8")
    except FileNotFoundError:
        return ""


def _get_version_from_pyproject() -> str:
    """Extract version from pyproject.toml."""
    pyproject = REPO_ROOT / "pyproject.toml"
    text = _read_text(pyproject)
    for line in text.splitlines():
        m = re.match(r'^version\s*=\s*"([^"]+)"', line)
        if m:
            return m.group(1)
    return ""


def check_readme() -> list[str]:
    """Check README.md for required markers."""
    errors = []
    readme_path = REPO_ROOT / "README.md"
    text = _read_text(readme_path)

    if not text:
        errors.append("README.md: file missing or empty")
        return errors

    # Normalize whitespace for matching
    # Strip blockquote markers before matching
    stripped = re.sub(r"^>\s*", "", text, flags=re.MULTILINE)
    flat = " ".join(stripped.split())

    if PRIVACY_SENTENCE not in flat:
        errors.append("README.md: missing exact privacy sentence")

    if not TIER_PATTERN.search(text):
        errors.append("README.md: missing Tier line (expected 'Tier: Tier-N')")

    return errors


def check_changelog() -> list[str]:
    """Check CHANGELOG.md exists and mentions current version."""
    errors = []
    changelog_path = REPO_ROOT / "CHANGELOG.md"
    text = _read_text(changelog_path)

    if not text:
        errors.append("CHANGELOG.md: file missing or empty")
        return errors

    version = _get_version_from_pyproject()
    if version and version not in text:
        errors.append(f"CHANGELOG.md: current version {version} not mentioned")

    return errors


def check_version_file() -> list[str]:
    """Check VERSION file has no leading 'v' (if it exists)."""
    errors = []
    version_path = REPO_ROOT / "VERSION"

    if not version_path.exists():
        return errors  # VERSION file is optional

    content = version_path.read_text(encoding="utf-8").strip()
    if content.startswith("v") or content.startswith("V"):
        errors.append(f"VERSION: leading 'v' prefix not allowed (found '{content}')")

    return errors


def main() -> int:
    """Run all presentation checks. Return 0 on pass, 1 on fail."""
    all_errors: list[str] = []
    all_errors.extend(check_readme())
    all_errors.extend(check_changelog())
    all_errors.extend(check_version_file())

    if all_errors:
        print("FAIL: Presentation gate")
        for err in all_errors:
            print(f"  - {err}")
        return 1

    print("PASS: Presentation gate")
    return 0


if __name__ == "__main__":
    sys.exit(main())
