"""Pre-commit hook entry point for Hikaflow flaky pattern detection.

Integrates with the official pre-commit framework (https://pre-commit.com/).

Usage:
    # Direct invocation
    hikaflow-precommit file1.py file2.py

    # Via pre-commit
    # .pre-commit-config.yaml
    repos:
      - repo: https://github.com/hikaflow/hikaflow
        rev: v1.0.0
        hooks:
          - id: hikaflow-flaky-check
            args: [--threshold, medium]
"""

from __future__ import annotations

import argparse
import sys
from collections.abc import Sequence
from pathlib import Path
from typing import List, Optional

from autodebug.hooks.scanner import FlakPatternScanner, PatternMatch, Severity


def main(argv: Optional[Sequence[str]] = None) -> int:
    """Main entry point for pre-commit hook.

    Args:
        argv: Command line arguments (defaults to sys.argv[1:])

    Returns:
        0 if no blocking issues, 1 if high-risk patterns detected
    """
    parser = argparse.ArgumentParser(
        description="Hikaflow pre-commit hook for flaky test pattern detection"
    )
    parser.add_argument(
        "files",
        nargs="*",
        help="Files to check (passed by pre-commit)",
    )
    parser.add_argument(
        "--threshold",
        choices=["low", "medium", "high"],
        default="high",
        help="Minimum severity to block commit (default: high)",
    )
    parser.add_argument(
        "--report-only",
        action="store_true",
        help="Report issues but don't block commit",
    )
    parser.add_argument(
        "--quiet",
        action="store_true",
        help="Only show blocking issues",
    )

    args = parser.parse_args(argv)

    if not args.files:
        return 0

    # Filter to test files only
    test_files = [
        Path(f)
        for f in args.files
        if f.endswith((".py", ".js", ".ts"))
        and ("test_" in f or "_test." in f or "/tests/" in f)
    ]

    if not test_files:
        return 0

    # Scan files
    threshold = Severity(args.threshold)
    scanner = FlakPatternScanner(threshold=Severity.LOW)  # Detect all, filter later
    all_matches: List[PatternMatch] = []

    for file_path in test_files:
        if file_path.exists():
            matches = scanner.scan_file(file_path)
            all_matches.extend(matches)

    if not all_matches:
        return 0

    # Filter by threshold for blocking decision
    blocking_threshold = Severity(args.threshold)
    severity_order = {Severity.LOW: 0, Severity.MEDIUM: 1, Severity.HIGH: 2}

    blocking_matches = [
        m
        for m in all_matches
        if severity_order[m.severity] >= severity_order[blocking_threshold]
    ]

    # Report
    if not args.quiet:
        report = scanner.format_report(all_matches)
        print(report)
    elif blocking_matches:
        # Quiet mode: only show blocking issues
        for m in blocking_matches:
            print(f"{m.file}:{m.line}: {m.severity.value.upper()} - {m.name}: {m.description}")

    # Determine exit code
    if args.report_only:
        return 0

    if blocking_matches:
        return 1

    return 0


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