"""Superpitch — inbound pitch screening agent."""

from __future__ import annotations

import sys

from superpitch import __version__
from superpitch.app_paths import bootstrap_user_files, log_sync_error
from superpitch.state import load_config, save_config
from superpitch.terminal_ui import run_interactive_app
from superpitch.updates import get_update_notice

try:
    from superpitch.sync import process_email_queue
    _SYNC_AVAILABLE = True
except ImportError:
    _SYNC_AVAILABLE = False


def maybe_startup_process(config: dict) -> int:
    """Process any queued emails before the TUI launches. Returns count added."""
    if not _SYNC_AVAILABLE:
        return 0
    if not config.get("signed_in") or not config.get("session_token"):
        return 0
    if not config.get("anthropic_api_key"):
        return 0
    try:
        return process_email_queue(config)
    except Exception as exc:
        log_sync_error("startup_process", exc)
        return 0


def main():
    # File / stdin mode — one-off analysis without opening the inbox
    if len(sys.argv) > 1:
        config = load_config()
        api_key = config.get("anthropic_api_key", "")
        if not api_key:
            print("No Anthropic API key configured. Run `superpitch` to set up.")
            raise SystemExit(1)

        from superpitch.process import process_file
        from superpitch.state import save_evidence_entry
        from superpitch.terminal_ui import print_packet_summary

        path = sys.argv[1]
        if path == "-":
            # stdin: write to temp file
            import tempfile, os
            text = sys.stdin.read()
            with tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False) as f:
                f.write(text)
                tmp = f.name
            packet = process_file(tmp, config.get("thesis", ""), api_key)
            os.unlink(tmp)
        else:
            packet = process_file(path, config.get("thesis", ""), api_key)

        if packet:
            print_packet_summary(packet)
            save_evidence_entry(packet, source_label=path)
        else:
            print("Could not extract evidence from that file.")
        return

    bootstrap_user_files()
    update_notice = get_update_notice()
    config = load_config()

    added = maybe_startup_process(config)
    if added:
        print(f"Processed {added} new pitch{'es' if added != 1 else ''}.")

    if update_notice:
        print(f"Update available: {update_notice} (current {__version__}). Type /upgrade inside the app.")

    run_interactive_app(config)


if __name__ == "__main__":
    main()
