import argparse
import sys
import ast
from pathlib import Path

from docugenius.core import (
    extract_definitions,
    get_function_metadata,
    generate_coverage_report,
    instrument_tree,
    generate_instrumented_code,
    validate_file,
)


def process_file(file_path: Path, style: str):
    """
    Process a single Python file.
    Returns (instrumented_code, coverage_percent, compliance_percent)
    """
    source = file_path.read_text(encoding="utf-8")

    tree = ast.parse(source)
    functions, _ = extract_definitions(tree)

    metadata = [get_function_metadata(func) for func in functions]

    coverage = generate_coverage_report(metadata)
    violations = validate_file(source)

    total = coverage["total_functions"]
    compliance = (
        round(((total - len(violations)) / total) * 100, 2)
        if total > 0 else 100.0
    )

    # Instrument
    instrumented_tree = instrument_tree(tree, style=style)
    instrumented_code = generate_instrumented_code(instrumented_tree)

    return instrumented_code, coverage["coverage_percent"], compliance


def main():
    parser = argparse.ArgumentParser(
        description="Automated Python Docstring Generator"
    )

    parser.add_argument(
        "files",
        nargs="+",
        help="Path(s) to Python file(s)"
    )

    parser.add_argument(
        "--style",
        choices=["google", "numpy", "reST"],
        default="google",
        help="Docstring style"
    )

    parser.add_argument(
        "--min-coverage",
        type=float,
        default=0,
        help="Minimum required documentation coverage percentage"
    )

    parser.add_argument(
        "--min-compliance",
        type=float,
        default=0,
        help="Minimum required PEP-257 compliance percentage"
    )

    args = parser.parse_args()

    overall_success = True

    for file_str in args.files:
        file_path = Path(file_str)

        if not file_path.exists():
            print(f"❌ File not found: {file_str}")
            overall_success = False
            continue

        try:
            instrumented_code, coverage, compliance = process_file(
                file_path, args.style
            )

            print(f"\n📄 File: {file_path}")
            print(f"Coverage: {coverage}%")
            print(f"Compliance: {compliance}%")

            if coverage < args.min_coverage:
                print(f"❌ Coverage below minimum ({args.min_coverage}%)")
                overall_success = False

            if compliance < args.min_compliance:
                print(f"❌ Compliance below minimum ({args.min_compliance}%)")
                overall_success = False

            # Print generated code
            print("\n--- Generated Code ---\n")
            print(instrumented_code)

        except Exception as e:
            print(f"❌ Error processing {file_str}: {e}")
            overall_success = False

    sys.exit(0 if overall_success else 1)


if __name__ == "__main__":
    main()
