#!/usr/bin/env python3
# File: scripts/update_version_metadata.py
# Purpose: Update MCP server version metadata in codex.mcp.json files
# Context: Synchronize version info between noveler hub and consumer projects

"""
MCPサーバーバージョン情報を管理するユーティリティ

使用例:
    python scripts/update_version_metadata.py --check
    python scripts/update_version_metadata.py --sync
    python scripts/update_version_metadata.py --version 0.0.4
"""

import argparse
import json
import subprocess
import sys
from datetime import datetime
from pathlib import Path


def get_noveler_version() -> str:
    """Get current noveler version from pyproject.toml"""
    pyproject = Path(__file__).parent.parent / "pyproject.toml"
    with open(pyproject, encoding="utf-8") as f:
        for line in f:
            if line.startswith('version = "'):
                return line.split('"')[1]
    raise ValueError("Version not found in pyproject.toml")


def get_git_tag() -> str:
    """Get current git tag"""
    try:
        result = subprocess.run(
            ["git", "describe", "--tags", "--abbrev=0"],
            check=False, capture_output=True,
            text=True,
            cwd=Path(__file__).parent.parent,
        )
        return result.stdout.strip() if result.returncode == 0 else "no-tag"
    except FileNotFoundError:
        return "no-tag"


def check_version_consistency() -> bool:
    """Check if pyproject.toml version matches git tag"""
    version = get_noveler_version()
    tag = get_git_tag()

    print("📋 Version Consistency Check\n")
    print(f"  pyproject.toml: v{version}")
    print(f"  git tag:        {tag}")

    if tag == "no-tag":
        print("\n  ❌ No git tag found")
        print(f"     Run: git tag v{version} && git push origin --tags")
        return False

    tag_version = tag.lstrip("v")
    if tag_version != version:
        print("\n  ❌ Version mismatch!")
        return False

    print("\n  ✅ Versions match")
    return True


def update_metadata_file(
    file_path: Path, version: str, metadata_key: str = "noveler_version"
) -> None:
    """Update codex.mcp.json metadata"""
    if not file_path.exists():
        print(f"  ⚠️  File not found: {file_path}")
        return

    with open(file_path, encoding="utf-8") as f:
        data = json.load(f)

    if "_metadata" not in data:
        data["_metadata"] = {}

    data["_metadata"][metadata_key] = version
    data["_metadata"]["pinned_date"] = datetime.now().strftime("%Y-%m-%d")

    with open(file_path, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

    print(f"  ✅ Updated: {file_path.relative_to(Path.cwd())}")


def sync_versions(version: str | None = None) -> None:
    """Sync version metadata across hub and projects"""
    if version is None:
        version = get_noveler_version()

    print(f"🔄 Syncing version metadata (v{version})\n")

    # Paths
    guide_mcp = Path(
        "C:/Users/bamboocity/OneDrive/Documents/9_小説/00_ガイド/codex.mcp.json"
    )
    muyuubyou_mcp = Path(
        "C:/Users/bamboocity/OneDrive/Documents/9_小説/11_夢遊病/codex.mcp.json"
    )

    # Update 00_ガイド
    print("Updating 00_ガイド:")
    update_metadata_file(guide_mcp, version, "noveler_version")

    # Update 夢遊病
    print("\nUpdating 夢遊病:")
    update_metadata_file(muyuubyou_mcp, version, "noveler_pinned_version")

    print("\n✨ Sync complete")


def main() -> int:
    """Main entry point"""
    parser = argparse.ArgumentParser(
        description="MCPサーバーnoveler バージョン管理ユーティリティ",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
使用例:
  python scripts/update_version_metadata.py --check
  python scripts/update_version_metadata.py --sync
  python scripts/update_version_metadata.py --version 0.0.4
        """,
    )

    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument(
        "--check",
        action="store_true",
        help="バージョン整合性をチェック",
    )
    group.add_argument(
        "--sync",
        action="store_true",
        help="メタデータを同期",
    )
    group.add_argument(
        "--version",
        type=str,
        help="新しいバージョンを指定",
    )

    args = parser.parse_args()

    try:
        if args.check:
            return 0 if check_version_consistency() else 1
        if args.sync:
            sync_versions()
            return 0
        if args.version:
            sync_versions(args.version)
            return 0
    except Exception as e:
        print(f"❌ Error: {e}", file=sys.stderr)
        return 1

    return 0


if __name__ == "__main__":
    sys.exit(main())
