#!/usr/bin/env python3
from pathlib import Path
import json
import re
import sys

try:
    import yaml
except Exception:
    yaml = None

ROOT = Path(__file__).resolve().parents[1]

required = [
    'SKILL.md',
    'INSTALL.md',
    'modules/ip-licensing-intake-router/SKILL.md',
    'modules/ip-licensing-project-workspace/SKILL.md',
    'modules/ip-licensing-source-research/SKILL.md',
    'modules/ip-licensing-trademark-logo-check/SKILL.md',
    'modules/ip-licensing-resource-value-map/SKILL.md',
    'modules/ip-licensing-gallery-system/SKILL.md',
    'modules/ip-licensing-product-mockup-system/SKILL.md',
    'modules/ip-licensing-final-introduction/SKILL.md',
    'modules/ip-licensing-delivery-qa/SKILL.md',
    'modules/ip-licensing-case-library/SKILL.md',
    'references/workflows/00-operating-model.md',
    'references/workflows/01-project-intake-and-setup.md',
    'references/workflows/02-stage-one-ip-value-analysis.md',
    'references/workflows/03-stage-two-gallery-system.md',
    'references/workflows/04-stage-three-product-mockup-system.md',
    'references/workflows/05-stage-four-final-introduction.md',
    'references/workflows/06-delivery-qa-and-handoff.md',
    'references/rules/reusable-experience-rules.md',
    'templates/PROJECT_CONTEXT.template.md',
    'templates/resource_card.template.md',
    'templates/gallery_direction_matrix.template.md',
    'templates/product_direction_matrix.template.md',
    'templates/final_delivery_qa.template.md',
]

errors = []
for rel in required:
    if not (ROOT / rel).exists():
        errors.append(f'missing {rel}')

for p in ROOT.rglob('SKILL.md'):
    text = p.read_text(encoding='utf-8')
    if not text.startswith('---'):
        errors.append(f'{p}: no frontmatter')
        continue
    m = re.search(r'\n---\s*\n', text[3:])
    if not m:
        errors.append(f'{p}: no frontmatter close')
        continue
    if yaml:
        fm = yaml.safe_load(text[3:m.start()+3])
        if not isinstance(fm, dict) or not fm.get('name') or not fm.get('description'):
            errors.append(f'{p}: missing name/description')


forbidden_terms = [
    'N' + 'AS', '/' + 'Users/', 'root_' + 'for_ai', 'AI' + '工作区',
    'IP授权介绍文档制作的四阶段' + '工作流',
    'gitee' + '.com', 'wwyl' + '2016', 'source-' + 'snapshots', 'archive/source-' + 'proof'
]
for p in ROOT.rglob('*'):
    if not p.is_file() or '.git' in p.parts:
        continue
    if p.suffix.lower() in {'.png', '.jpg', '.jpeg', '.webp', '.gif'}:
        continue
    text = p.read_text(encoding='utf-8', errors='ignore')
    for term in forbidden_terms:
        if term in text:
            errors.append(f'{p.relative_to(ROOT)}: forbidden local/storage term {term!r}')

experience = (ROOT / 'references/rules/reusable-experience-rules.md').read_text(encoding='utf-8')
key_phrases = [
    '100 字以内', '商标与 Logo', '宗教', '画风分类', '标贴', '封签', '边框', '腰封',
    '二维平面资产', '两轮选择', '单张确认', 'A/B', '毛绒', '3C', '丝巾',
    '大标题短', '孤字', 'IP 气质', '合作路径固定为 8 步', '可见文字 QA',
    '提示词', 'TODO', '二维码', '确认版', 'Common Errors'
]
for phrase in key_phrases:
    if phrase not in experience:
        errors.append(f'references/rules/reusable-experience-rules.md: missing key phrase {phrase!r}')


workflow_phrase_checks = {
    'references/workflows/01-project-intake-and-setup.md': [
        '用户没说完', '重做', 'candidate', '确认版', '安装配置'
    ],
    'references/workflows/02-stage-one-ip-value-analysis.md': [
        '100 字以内', '商标与 Logo', '场地资源', '文物资源', '核心主打理由', '宗教', '媒体矩阵', '文创产品', '阶段一交付与自审'
    ],
    'references/workflows/03-stage-two-gallery-system.md': [
        '画风分类', '标签', '标贴', '封签', '边框', '腰封', '二维', '两轮选择', '单张确认', 'final_selected', '用户反馈处理'
    ],
    'references/workflows/04-stage-three-product-mockup-system.md': [
        'A/B', '礼盒', '毛绒', '3C', '丝巾', '冰箱贴', '旅行章', 'selected', 'final', '产品形态是否真实'
    ],
    'references/workflows/05-stage-four-final-introduction.md': [
        '品牌方', '大标题短', '孤字', 'IP 气质', '代表资源', '图库精选区', '产品应用区', '合作路径', '8 步', '二维码', '可见文字 QA', '提示词', 'TODO'
    ],
    'references/workflows/06-delivery-qa-and-handoff.md': [
        '可见文字 QA', '孤字', '二维码', 'final_selected', 'selected', '确认版', 'Common Errors and Fixes'
    ],
}
for rel, phrases in workflow_phrase_checks.items():
    text = (ROOT / rel).read_text(encoding='utf-8')
    for phrase in phrases:
        if phrase not in text:
            errors.append(f'{rel}: missing embedded experience phrase {phrase!r}')


# Installation variables belong to INSTALL.md / references/configuration / templates only,
# not to stage workflows or module runtime instructions.
for root_name in ['references/workflows', 'modules']:
    root_dir = ROOT / root_name
    if not root_dir.exists():
        continue
    for p in root_dir.rglob('*.md'):
        text = p.read_text(encoding='utf-8', errors='ignore')
        for marker in ['IP_LICENSING_', 'project://', 'case-library://', 'reference-assets://', 'public-assets://']:
            if marker in text:
                errors.append(f'{p.relative_to(ROOT)}: install config marker {marker!r} must stay in INSTALL/config templates, not runtime workflow/module')

manifest = json.loads((ROOT / 'skillpack.manifest.json').read_text(encoding='utf-8'))

expected_resource_mcp = {
    'server': 'studio_resource_library',
    'url': 'http://100.113.171.115:18871/mcp',
    'default_domain': 'authorization',
    'default_library_id': 'ip-product-reference-library',
}
resource_mcp = manifest.get('storage_configuration', {}).get('default_resource_library_mcp', {})
for key, value in expected_resource_mcp.items():
    if resource_mcp.get(key) != value:
        errors.append(f'skillpack.manifest.json: default_resource_library_mcp.{key} must be {value!r}')

env_text = (ROOT / 'templates/ip-licensing.env.example').read_text(encoding='utf-8')
for key, value in expected_resource_mcp.items():
    env_name = {
        'server': 'IP_LICENSING_RESOURCE_LIBRARY_MCP_SERVER',
        'url': 'IP_LICENSING_RESOURCE_LIBRARY_MCP_URL',
        'default_domain': 'IP_LICENSING_RESOURCE_LIBRARY_DEFAULT_DOMAIN',
        'default_library_id': 'IP_LICENSING_RESOURCE_LIBRARY_DEFAULT_LIBRARY_ID',
    }[key]
    if f'{env_name}={value}' not in env_text:
        errors.append(f'templates/ip-licensing.env.example: missing default {env_name}={value}')

storage_config = json.loads((ROOT / 'templates/storage-config.example.json').read_text(encoding='utf-8'))
for key, value in expected_resource_mcp.items():
    if storage_config.get('resource_library_mcp', {}).get(key) != value:
        errors.append(f'templates/storage-config.example.json: resource_library_mcp.{key} must be {value!r}')

if errors:
    print('\n'.join(errors))
    sys.exit(1)

print('ip-licensing-skillpack-ok')
