#!/usr/bin/env python3
"""
Quality Gate - Per-batch validation with pattern-based transition checks.

CONSOLIDATION NOTE:
  Canonical implementation lives in .claude/hooks/quality_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:
    quality_gate.py <project_path> <batch_start> <batch_end> [prev_batch_end]

The hooks version uses a batch_number interface:
    quality_gate.py <project_path> <batch_number>

Both interfaces are supported. When called with the batch_start/batch_end
interface, this wrapper converts to the hooks batch_number format.

Exit codes:
- 0: All checks pass
- 1: Hard gate failure (must fix before continuing)
- 2: Warnings only (can continue but should review)
"""

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 that import from here.
# The hooks version has a different internal API than the old tools/
# version. We re-export what the hooks version provides.
try:
    from quality_gate import (
        extract_script_content,
        extract_cliffhanger_metadata,
        detect_cliffhanger_type,
        detect_hook_type,
        check_pattern_variety,
        check_emotional_beats,
        check_dangling_cause,
        check_transition_patterns,
        check_must_contain,
        calculate_ratios,
        main as _hooks_main,
    )
except ImportError as e:
    print(f"ERROR: Cannot import canonical quality_gate from {_hooks_dir}")
    print(f"       Import error: {e}")
    print(f"       Ensure .claude/hooks/quality_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. Supports two calling conventions:

    Original tools/ interface (3+ args):
        quality_gate.py <project_path> <batch_start> <batch_end> [prev_batch_end]

    Hooks interface (2 args):
        quality_gate.py <project_path> <batch_number>

    When called with batch_start/batch_end, converts to batch_number by
    computing: batch_number = (batch_start - 1) // 5 + 1
    Then delegates to the canonical hooks implementation.
    """
    if len(sys.argv) < 3:
        print("Usage: quality_gate.py <project_path> <batch_start> <batch_end> [prev_batch_end]")
        print("   or: quality_gate.py <project_path> <batch_number>")
        print()
        print("Example: quality_gate.py ./leviathan 1 5")
        print("Example: quality_gate.py ./leviathan 6 10 5")
        print("Example: quality_gate.py ./leviathan 1")
        sys.exit(1)

    if len(sys.argv) == 3:
        # Hooks-style call: quality_gate.py <project_path> <batch_number>
        # Delegate directly
        _hooks_main()
    else:
        # Original tools/ style: quality_gate.py <project_path> <batch_start> <batch_end>
        # Convert to batch_number and delegate
        batch_start = int(sys.argv[2])
        batch_number = (batch_start - 1) // 5 + 1

        # Rewrite sys.argv to match hooks interface, then call hooks main
        sys.argv = [sys.argv[0], sys.argv[1], str(batch_number)]
        _hooks_main()


if __name__ == '__main__':
    main()
