from __future__ import annotations

import json
import re
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
EXCLUDED_DIRS = {".git", ".venv", "venv", "build", "dist", "Output", "__pycache__"}
TEXT_SUFFIXES = {".py", ".json", ".txt", ".md", ".bat", ".iss", ".spec", ".ini", ".toml", ".yaml", ".yml", ".env"}
OPENAI_KEY = re.compile(r"sk-[A-Za-z0-9_-]{20,}")
NONEMPTY_JSON_KEY = re.compile(r'"api_key"\s*:\s*"([^"\\]+)"', re.IGNORECASE)

problems: list[str] = []
for path in ROOT.rglob("*"):
    if not path.is_file() or any(part in EXCLUDED_DIRS for part in path.parts):
        continue
    if path.suffix.lower() not in TEXT_SUFFIXES and path.name not in {"Dockerfile"}:
        continue
    try:
        text = path.read_text(encoding="utf-8")
    except UnicodeDecodeError:
        continue
    if OPENAI_KEY.search(text):
        problems.append(f"OpenAI-like secret found: {path.relative_to(ROOT)}")
    for match in NONEMPTY_JSON_KEY.finditer(text):
        value = match.group(1).strip()
        if value and value not in {"YOUR_API_KEY", "YOUR_OPENAI_API_KEY", "example"}:
            problems.append(f"Non-empty api_key found: {path.relative_to(ROOT)}")

# The compiled package must never contain a user settings file.
for forbidden in (ROOT / "settings.json", ROOT / "app" / "settings.json", ROOT / ".env"):
    if forbidden.exists():
        problems.append(f"Forbidden local settings file included: {forbidden.relative_to(ROOT)}")

if problems:
    print("SECRET CHECK FAILED")
    for problem in problems:
        print(f"- {problem}")
    raise SystemExit(1)

print("SECRET CHECK OK: no API key or user settings are included in the project.")
