#!/usr/bin/env python
"""
Claude Code settings.local.json 驗證與修復工具

用途：檢查 settings.local.json 是否有效，自動修復常見的引號跳脫錯誤

使用方式：
    python validate_settings.py          # 只驗證
    python validate_settings.py --fix    # 驗證並自動修復
"""

import sys
import json
import re
from pathlib import Path

sys.stdout.reconfigure(encoding='utf-8')

SETTINGS_FILE = Path(__file__).parent / 'settings.local.json'

# 常見的錯誤模式和修復
ERROR_PATTERNS = [
    # 路徑結尾多餘的跳脫引號: raw\"\" → raw\"
    (r'(\\\\[^\\]+)\\"\\"\)', r'\1\\")'),
    # 雙重跳脫引號: \\"\\" → \\"
    (r'\\\\"\\\\"\)', r'\\\\")'),
]


def validate_json(filepath: Path) -> tuple[bool, str | None]:
    """驗證 JSON 檔案是否有效"""
    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            json.load(f)
        return True, None
    except json.JSONDecodeError as e:
        return False, str(e)
    except FileNotFoundError:
        return False, "檔案不存在"


def find_quote_issues(content: str) -> list[str]:
    """找出可能的引號問題"""
    issues = []

    # 檢查 Bash 權限模式中的引號
    bash_patterns = re.findall(r'"Bash\([^"]*(?:\\.[^"]*)*"', content)

    for pattern in bash_patterns:
        # 檢查是否有連續的跳脫引號（可能是錯誤）
        if re.search(r'\\"\\"\)', pattern):
            issues.append(f"發現可能的雙引號錯誤: ...{pattern[-50:]}")

    return issues


def fix_content(content: str) -> tuple[str, int]:
    """嘗試修復常見的引號錯誤"""
    fixed_content = content
    fix_count = 0

    for pattern, replacement in ERROR_PATTERNS:
        new_content = re.sub(pattern, replacement, fixed_content)
        if new_content != fixed_content:
            fix_count += 1
            fixed_content = new_content

    return fixed_content, fix_count


def main():
    fix_mode = '--fix' in sys.argv

    print(f"🔍 檢查 {SETTINGS_FILE.name}...")
    print()

    if not SETTINGS_FILE.exists():
        print("❌ 檔案不存在")
        return 1

    # 讀取原始內容
    with open(SETTINGS_FILE, 'r', encoding='utf-8') as f:
        content = f.read()

    # 驗證 JSON
    is_valid, error = validate_json(SETTINGS_FILE)

    if is_valid:
        print("✅ JSON 格式有效")

        # 即使有效，也檢查潛在問題
        issues = find_quote_issues(content)
        if issues:
            print()
            print("⚠️  發現潛在問題（但 JSON 仍有效）:")
            for issue in issues:
                print(f"   - {issue}")

        return 0

    print(f"❌ JSON 格式無效: {error}")
    print()

    # 檢查具體問題
    issues = find_quote_issues(content)
    if issues:
        print("🔎 發現的問題:")
        for issue in issues:
            print(f"   - {issue}")
        print()

    if not fix_mode:
        print("💡 提示: 使用 --fix 參數嘗試自動修復")
        return 1

    # 嘗試修復
    print("🔧 嘗試自動修復...")
    fixed_content, fix_count = fix_content(content)

    if fix_count == 0:
        print("❌ 無法自動修復，需要手動檢查")
        return 1

    # 驗證修復後的內容
    try:
        json.loads(fixed_content)
    except json.JSONDecodeError:
        print("❌ 修復後 JSON 仍無效，需要手動檢查")
        return 1

    # 寫入修復後的內容
    with open(SETTINGS_FILE, 'w', encoding='utf-8') as f:
        f.write(fixed_content)

    print(f"✅ 已修復 {fix_count} 個問題")
    return 0


if __name__ == '__main__':
    sys.exit(main())
