import argparse
import json
import sys
import traceback
from acquiscan.config import Config
from acquiscan.exhibit_scan import run_structured_exhibit_scan
from acquiscan.llm_scan import run_llm_scan

def format_results(results, mode):
    company = results.get("company", "?")
    lines = []
    for entry in results.get("portfolio", []):
        form = entry.get("form_type", "?")
        date = entry.get("filing_date", "?")
        name = entry.get("name", "?")
        lines.append(f"[{company}] [{mode}] [{form}] [{date}] {name}")
    return "\n".join(lines)

def main():
    parser = argparse.ArgumentParser(
        description="AcquiScan - Extract acquisition information from SEC filings",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Modes:
  exhibits  - Extract subsidiaries from EX-21 and EX-8 exhibit documents (default)
  llm       - Use an LLM to extract structured acquisition data from filings

Examples:
  acquiscan "Apple"
  acquiscan "Meta" --mode llm
  acquiscan "Meta" --mode llm --json --output results.json
"""
    )

    parser.add_argument("company", help="Company name to search for")
    parser.add_argument("--mode", "-m", choices=["exhibits", "llm"], default="exhibits", help="Extraction mode (default: exhibits)")
    parser.add_argument("--json", "-j", action="store_true", help="Output as JSON")
    parser.add_argument("--output", "-o", type=str, default=None, help="Output file path (default: stdout)")
    parser.add_argument("--silent", "-s", action="store_true", help="Suppress progress output")
    parser.add_argument("--from-date", type=str, default=None, help="Only include filings on or after this date (YYYY-MM-DD)")
    parser.add_argument("--to-date", type=str, default=None, help="Only include filings on or before this date (YYYY-MM-DD)")
    parser.add_argument("--include-filings", action="store_true", help="Include per-filing breakdown in JSON output (LLM mode only)")
    parser.add_argument("--include-excerpts", action="store_true", help="Include excerpts in JSON output (LLM mode only, implies --include-filings)")

    args = parser.parse_args()

    if args.include_excerpts:
        args.include_filings = True

    config = Config.load()

    if args.mode == "llm" and not config.llm_api_key:
        print(f"Error: llm_api_key not set in {Config.CONFIG_PATH}", file=sys.stderr)
        sys.exit(1)

    try:
        if args.mode == "exhibits":
            results = run_structured_exhibit_scan(args.company, config, silent=args.silent, from_date=args.from_date, to_date=args.to_date)
        else:
            results = run_llm_scan(args.company, config, silent=args.silent, from_date=args.from_date, to_date=args.to_date, include_excerpts=args.include_excerpts, include_filings=args.include_filings)

        if args.json:
            output = json.dumps(results, indent=2)
        else:
            output = format_results(results, args.mode)

        if args.output:
            with open(args.output, 'w', encoding='utf-8') as f:
                f.write(output)
            print(f"Results written to {args.output}", file=sys.stderr)
        else:
            print(output)

    except KeyboardInterrupt:
        print("\nInterrupted", file=sys.stderr)
        sys.exit(130)
    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        if not args.silent:
            traceback.print_exc()
        sys.exit(1)
