from __future__ import annotations

import ast
import json
import pathlib
import sys

root = pathlib.Path(__file__).resolve().parents[1]
errors: list[str] = []

for path in root.rglob("*.py"):
    if any(part in {".venv", "node_modules"} for part in path.parts):
        continue
    try:
        ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
    except SyntaxError as exc:
        errors.append(str(exc))

for path in [root / "frontend/package.json", root / "frontend/public/manifest.webmanifest"]:
    try:
        json.loads(path.read_text(encoding="utf-8"))
    except Exception as exc:  # noqa: BLE001 - aggregate release check
        errors.append(f"{path}: {exc}")

feature_text = (root / "frontend/src/feature-catalogue.js").read_text(encoding="utf-8")
for required in [
    "research",
    "websites",
    "code-interpreter",
    "docs",
    "slides",
    "sheets",
    "vision",
    "image-studio",
    "video-studio",
    "voice",
    "files",
    "artifacts",
    "agent",
    "swarm",
    "tools",
    "memory",
    "skills",
    "evaluations",
    "batch",
    "fine-tuning",
    "administration",
]:
    if f"id:'{required}'" not in feature_text:
        errors.append(f"missing feature catalogue entry: {required}")
for available in ["chat", "files", "code-interpreter", "memory", "skills", "tools", "voice", "websites", "swarm"]:
    marker = f"id:'{available}'"
    start = feature_text.find(marker)
    snippet = feature_text[start : start + 800] if start >= 0 else ""
    if "status:'available'" not in snippet:
        errors.append(f"operational module is not marked available: {available}")
if "status:'placeholder'" not in feature_text:
    errors.append("truthful placeholder status is missing")


lock_path = root / "config/feature-locks.json"
try:
    feature_locks = json.loads(lock_path.read_text(encoding="utf-8"))
except Exception as exc:  # noqa: BLE001
    errors.append(f"invalid feature-lock register: {exc}")
    feature_locks = {}
if feature_locks.get("implementation_order") != ["tools-runtime", "conversation-mode", "website-builder", "swarm"]:
    errors.append("locked implementation order changed")
lock_text = json.dumps(feature_locks, sort_keys=True)
for required in [
    "moonshotai/Kimi-K2.6",
    "openai/whisper-large-v3",
    "cartesia/sonic-3",
    "Flask WebSocket gateway",
    "true barge-in",
    "Kimi generation",
    "mobile-first wizard",
    "file leases",
]:
    if required not in lock_text:
        errors.append(f"missing feature lock: {required}")
for required in [
    "Whisper Large v3 exclusively for STT",
    "Cartesia Sonic 3 exclusively for TTS",
    "Sonic context.cancel",
    "Kimi generation cancellation",
    "Project creation and safe text ZIP import",
    "Central versioned registry",
    "Workspace file leases",
    "Agent-attributed tool records",
]:
    if required not in feature_text:
        errors.append(f"operational feature catalogue contract missing: {required}")

backend_text = (root / "src/kimu/app.py").read_text(encoding="utf-8")
for route in [
    "/api/v1/files",
    "/api/v1/chat/runs",
    "/api/v1/jobs",
    "/api/v1/code/runs",
    "/api/v1/memories",
    "/api/v1/skills",
    "/api/v1/settings",
    "/api/v1/admin/summary",
    "/api/v1/sync/status",
    "/api/v1/sync/pull",
    "/api/v1/sync/snapshot",
]:
    if route not in backend_text:
        errors.append(f"missing operational API route: {route}")
for module in ["fileops.py", "tci.py", "crypto.py", "artifact_storage.py", "tool_runtime.py", "advanced.py", "conversation_gateway.py"]:
    if not (root / "src/kimu" / module).is_file():
        errors.append(f"missing backend module: {module}")


advanced_text = (root / "src/kimu/advanced.py").read_text(encoding="utf-8")
conversation_text = (root / "src/kimu/conversation_gateway.py").read_text(encoding="utf-8")
conversation_client_text = (root / "frontend/src/conversation-client.js").read_text(encoding="utf-8")
for required in [
    "/api/v1", "/websites/import", "/websites/<project_id>/test", "workspace_file_leases",
    "swarm_checkpoints", "TOOL_DEFINITIONS", "register_conversation_gateway",
]:
    if required not in advanced_text:
        errors.append(f"missing Increment 41-44 backend contract: {required}")
for required in ["context.cancel", "input_text_buffer.clear", "KIMU_CSRF_FAILED", "stt_reader", "tts_reader"]:
    if required not in conversation_text:
        errors.append(f"missing Conversation Mode contract: {required}")
for required in ["getCsrf()", "barge_in", "pcm.buffer", "clearAudio", "PcmPlaybackQueue"]:
    if required not in conversation_client_text:
        errors.append(f"missing browser conversation contract: {required}")
model_text = (root / "src/kimu/models.py").read_text() + (root / "src/kimu/config.py").read_text()
for required in [
    "moonshotai/Kimi-K2.6",
    "moonshotai/Kimi-K2.7-Code",
    "reasoning_toggle=False",
    "preserve_reasoning=True",
]:
    if required not in model_text:
        errors.append(f"missing model contract: {required}")

built_text = "\n".join(
    path.read_text(encoding="utf-8", errors="ignore")
    for path in [root / "static/index.html", root / "static/app.js", root / "static/styles.css"]
    if path.is_file()
)
if "class PcmPlaybackQueue" not in built_text:
    errors.append("Conversation Mode client was not included in the vendored production bundle")

for forbidden in [
    "unpkg.com",
    "cdn.jsdelivr.net",
    "cdnjs.cloudflare.com",
    "fonts.googleapis.com",
    "fonts.gstatic.com",
]:
    if forbidden in built_text:
        errors.append(f"runtime CDN reference found: {forbidden}")


for required in [
    "KIMU_MASTER_KEY",
    "AES-256-GCM",
    "offline-queue",
    "KIMU_SYNC_CONFLICT",
    "client_operation_id",
]:
    sources = "\n".join(
        path.read_text(encoding="utf-8", errors="ignore")
        for path in [
            root / ".env.example",
            root / "README.md",
            root / "frontend/src/offline.js",
            root / "src/kimu/app.py",
            root / "src/kimu/crypto.py",
        ]
        if path.is_file()
    )
    if required not in sources:
        errors.append(f"missing encrypted/offline sync contract: {required}")

if "offline-queue" not in built_text or "function queueOperation" not in built_text:
    errors.append("offline queue was not included in the vendored production bundle")
if "from './offline.js'" in built_text or 'from "./offline.js"' in built_text:
    errors.append("unresolved ESM import found in the classic production bundle")
if '"increment": 46' not in backend_text:
    errors.append("health endpoint does not report Increment 46")

sys.path.insert(0, str(root / "src"))
from kimu.db import connect, initialise  # noqa: E402
from kimu.models import build_profiles, normalise_preferences  # noqa: E402

path = root / "instance/check.sqlite3"
path.parent.mkdir(parents=True, exist_ok=True)
path.unlink(missing_ok=True)
initialise(path)
db = connect(path)
if db.execute("PRAGMA integrity_check").fetchone()[0] != "ok":
    errors.append("sqlite integrity failed")
if db.execute("PRAGMA journal_mode").fetchone()[0].lower() != "wal":
    errors.append("sqlite WAL mode failed")
tables = {
    row[0]
    for row in db.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()
}
for table in ["files", "message_attachments", "jobs", "job_events", "memories", "skills", "audit_log", "sync_operations", "sync_changes", "workspaces", "tool_operations", "website_projects", "website_test_results", "swarms", "swarm_checkpoints", "workspace_file_leases", "audio_sessions"]:
    if table not in tables:
        errors.append(f"missing database table: {table}")
db.close()
path.unlink(missing_ok=True)
(path.parent / "check.sqlite3-wal").unlink(missing_ok=True)
(path.parent / "check.sqlite3-shm").unlink(missing_ok=True)

profiles = build_profiles(
    {
        "K26_MODEL_ID": "moonshotai/Kimi-K2.6",
        "K27_MODEL_ID": "moonshotai/Kimi-K2.7-Code",
        "K27_CONFIGURED": True,
        "TOGETHER_API_KEY": "x",
        "FAKE_PROVIDER": False,
    }
)
locked = normalise_preferences(
    profiles["k2.7-code"], {"reasoning_enabled": False, "temperature": 0.2}
)
if locked["reasoning_enabled"] is not True:
    errors.append("K2.7 reasoning lock failed")
if locked["temperature"] != 1.0:
    errors.append("K2.7 temperature lock failed")

if errors:
    print("\n".join(errors))
    raise SystemExit(1)
print("STATIC_AND_CORE_CHECKS_PASS")
