#!/usr/bin/env python3
"""
Transition Gate - Full series transition validation (runs after episode 60).

CONSOLIDATION NOTE:
  Canonical implementation lives in .claude/hooks/transition_gate.py
  This wrapper delegates to the canonical version to avoid drift.
  The hooks version is used by save_checkpoint.py in the generation pipeline.

This wrapper preserves the original tools/ CLI interface:
    transition_gate.py <project_path>              # Generate report
    transition_gate.py <project_path> --check      # Check and exit with code
    transition_gate.py <project_path> --fix-list   # Output fix commands
    transition_gate.py <project_path> --json       # Output report as JSON

Exit codes (with --check):
- 0: All transitions pass automated checks
- 1: Hard failures found (must fix)
- 2: Needs AI review (semantic issues flagged)
"""

import sys
from pathlib import Path

# Add .claude/hooks to sys.path so we can import the canonical implementation
_project_root = Path(__file__).resolve().parent.parent.parent
_hooks_dir = _project_root / ".claude" / "hooks"
if str(_hooks_dir) not in sys.path:
    sys.path.insert(0, str(_hooks_dir))

# Import canonical functions for use by other scripts
try:
    from transition_gate import (
        extract_section,
        extract_location,
        load_episode,
        check_pattern_violations,
        check_semantic_issues,
        run_full_validation,
        print_report,
        print_fix_commands,
        main as _hooks_main,
    )
except ImportError as e:
    print(f"ERROR: Cannot import canonical transition_gate from {_hooks_dir}")
    print(f"       Import error: {e}")
    print(f"       Ensure .claude/hooks/transition_gate.py exists.")
    sys.exit(1)

# Remove hooks dir from path to avoid polluting other imports
if sys.path[0] == str(_hooks_dir):
    sys.path.pop(0)


def main():
    """
    CLI entry point. Delegates to the canonical hooks implementation.

    The tools/ and .claude/hooks/ versions share the same CLI interface:
        transition_gate.py <project_path> [--check] [--fix-list]

    The tools/ version previously also supported --json.
    The hooks version handles --check and --fix-list. For --json, we add
    support here by calling the canonical validation and serializing.
    """
    if '--json' in sys.argv and '--check' not in sys.argv and '--fix-list' not in sys.argv:
        # Handle --json mode which the hooks version may not support
        import json
        from datetime import datetime

        if len(sys.argv) < 2:
            print("Usage: transition_gate.py <project_path> [--check] [--fix-list] [--json]")
            sys.exit(1)

        project_path = Path(sys.argv[1]).resolve()
        result = run_full_validation(project_path)

        report = {
            'timestamp': datetime.now().isoformat(),
            'project': str(project_path),
            'total_transitions': result['summary']['total_transitions'],
            'hard_fails': result['summary']['hard_fail_count'],
            'reviews_needed': result['summary']['review_count'],
            'passed': result['passed'],
            'hard_fail_details': result['hard_fails'],
            'review_details': result['reviews'],
        }
        print(json.dumps(report, indent=2))

        if '--check' in sys.argv:
            if not result['passed']:
                sys.exit(1)
            elif result['summary']['review_count'] > 0:
                sys.exit(2)
            else:
                sys.exit(0)
    else:
        # Delegate to canonical implementation
        _hooks_main()


if __name__ == '__main__':
    main()
