"""
CLI interface for ai-text-audit.
"""

import sys
import json
import argparse
from pathlib import Path
from . import __version__
from .auditor import Auditor


VERDICT_EMOJI = {
    "likely_human": "🟢",
    "possibly_ai": "🟡",
    "likely_ai": "🤖",
}

SEVERITY_ICONS = {
    "low": "💡",
    "medium": "⚡",
    "high": "⚠️",
    "critical": "🚨",
}


def format_terminal(result, filepath: str = "-", verbose: bool = False) -> str:
    """Format result for terminal display."""
    lines = []
    emoji = VERDICT_EMOJI.get(result.verdict, "❓")

    lines.append(f"🦞 AI Text Audit — {filepath}")
    lines.append("━" * 50)
    lines.append(f"Score: {result.score} / 100  →  {emoji} {result.verdict.replace('_', ' ').title()}")
    lines.append(f"Words: {result.word_count}  |  Patterns matched: {len(result.patterns)}")
    lines.append("")

    if result.patterns:
        lines.append("Patterns detected:")
        for p in result.patterns:
            icon = SEVERITY_ICONS.get(p.severity, "•")
            count_str = f"(×{p.count})"
            name_display = f"{p.name:25s}"
            lines.append(f"  {icon}  {name_display} {count_str:>6s}")
            if verbose:
                lines.append(f"       {p.description}")
                if p.matches:
                    sample = p.matches[0][:60]
                    lines.append(f"       Sample: \"{sample}\"")
        lines.append("")

    if result.suggestions:
        lines.append("Suggestions:")
        for i, s in enumerate(result.suggestions[:5], 1):
            lines.append(f"  {i}. {s}")
        lines.append("")

    lines.append("━" * 50)
    return "\n".join(lines)


def main():
    parser = argparse.ArgumentParser(
        prog="ai-audit",
        description="🦞 Detect AI writing patterns. Make text human again.",
    )
    parser.add_argument(
        "input",
        nargs="?",
        default="-",
        help="File to analyze (use '-' for stdin)",
    )
    parser.add_argument(
        "--version", "-V",
        action="version",
        version=f"%(prog)s {__version__}",
    )
    parser.add_argument(
        "--json", "-j",
        action="store_true",
        dest="output_json",
        help="Output results as JSON",
    )
    parser.add_argument(
        "--verbose", "-v",
        action="store_true",
        help="Show detailed pattern descriptions",
    )
    parser.add_argument(
        "--threshold", "-t",
        type=float,
        default=60.0,
        help="AI detection threshold (0-100, default: 60)",
    )
    parser.add_argument(
        "--score-only", "-s",
        action="store_true",
        help="Output only the score number",
    )
    parser.add_argument(
        "--batch", "-b",
        action="store_true",
        help="Process directory (input must be a directory)",
    )
    parser.add_argument(
        "--language", "-l",
        choices=["en", "zh", "all"],
        default="all",
        help="Language patterns to use (default: all)",
    )
    parser.add_argument(
        "--config", "-c",
        help="Path to custom patterns YAML config",
    )
    parser.add_argument(
        "--extensions", "-e",
        default=".md,.txt,.rst",
        help="File extensions for batch mode (default: .md,.txt,.rst)",
    )
    parser.add_argument(
        "--exit-code",
        action="store_true",
        help="Exit with code 1 if score exceeds threshold",
    )

    args = parser.parse_args()

    auditor = Auditor(
        patterns_file=args.config,
        language=args.language,
        threshold_ai=args.threshold,
    )

    # Determine input source
    if args.input == "-":
        text = sys.stdin.read()
        if not text.strip():
            print("Error: No input provided", file=sys.stderr)
            sys.exit(1)
        result = auditor.analyze(text)
        filepath = "(stdin)"
    elif args.batch:
        input_path = Path(args.input)
        if not input_path.is_dir():
            print(f"Error: {args.input} is not a directory", file=sys.stderr)
            sys.exit(1)
        extensions = args.extensions.split(",")
        results = auditor.analyze_dir(input_path, extensions)
        if args.output_json:
            print(json.dumps([r.to_dict() for r in results], indent=2, ensure_ascii=False))
        else:
            for r in results:
                filepath = r.details.get("file", "?")
                print(format_terminal(r, filepath, args.verbose))
                print()
        return
    else:
        input_path = Path(args.input)
        if not input_path.exists():
            print(f"Error: File not found: {args.input}", file=sys.stderr)
            sys.exit(1)
        result = auditor.analyze_file(input_path)
        filepath = args.input

    # Output
    if args.score_only:
        print(int(result.score))
    elif args.output_json:
        output = result.to_dict()
        output["file"] = filepath
        print(json.dumps(output, indent=2, ensure_ascii=False))
    else:
        print(format_terminal(result, filepath, args.verbose))

    # Exit code
    if args.exit_code and result.score >= args.threshold:
        sys.exit(1)


if __name__ == "__main__":
    main()
