from pathlib import Path
import json
import re

ROOT = Path(__file__).resolve().parents[1]
required = [
    'app/pubspec.yaml',
    'app/lib/main.dart',
    'app/lib/screens/home_screen.dart',
    'app/lib/models/klt_models.dart',
    'app/lib/services/lambda_engine.dart',
    'app/lib/services/project_engine.dart',
    'app/lib/services/visualization_service.dart',
    'app/lib/widgets/klt_visual_painters.dart',
    'app/lib/l10n/app_strings.dart',
    'core_python/klt51_core.py',
    'core_python/klt51_cli.py',
    'examples/demo_project.json',
    'examples/out/result.json',
    'examples/out/report.md',
    'examples/out/scheme.svg',
    'examples/out/blueprint.svg',
    'examples/out/graph.svg',
    'docs/KLT5_1_TZ_RU.md',
    'docs/KLT5_1_TZ_RU.pdf',
    'docs/KLT5_1_PRINCIPLES_RU.md',
    'docs/KLT5_1_PRINCIPLES_RU.pdf',
    'docs/KLT5_1_CAPABILITIES_RU.md',
    'docs/KLT5_1_CAPABILITIES_RU.pdf',
]
missing = [p for p in required if not (ROOT / p).exists()]
if missing:
    raise SystemExit('Missing files: ' + ', '.join(missing))

for rel in ['app/lib/main.dart','app/lib/screens/home_screen.dart','app/lib/services/project_engine.dart','app/lib/services/visualization_service.dart','app/lib/widgets/klt_visual_painters.dart']:
    text = (ROOT / rel).read_text(encoding='utf-8')
    pairs = [('(',')'),('{','}'),('[',']')]
    for a,b in pairs:
        if text.count(a) != text.count(b):
            raise SystemExit(f'Unbalanced {a}{b} in {rel}: {text.count(a)} != {text.count(b)}')

l10n = (ROOT / 'app/lib/l10n/app_strings.dart').read_text(encoding='utf-8')
for lang in ['ru','en','zh']:
    if f"'{lang}'" not in l10n:
        raise SystemExit(f'Missing language {lang}')

res = json.loads((ROOT / 'examples/out/result.json').read_text(encoding='utf-8'))
if res['pix_count'] < 1 or res['defect_count'] < 1:
    raise SystemExit('Smoke result is not meaningful')

for svg in ['scheme.svg','blueprint.svg','graph.svg']:
    content = (ROOT / 'examples/out' / svg).read_text(encoding='utf-8')
    if '<svg' not in content or '</svg>' not in content:
        raise SystemExit(f'Invalid SVG: {svg}')

print('KLT5.1 package structural validation: OK')
print(f"PIX={res['pix_count']} defects={res['defect_count']} lambda={res['lambda_count']} CRI={res['cri']:.4f}")
