"""Superpitch terminal entrypoint."""

from __future__ import annotations

import sys

from superpitch import __version__
from superpitch.app_paths import bootstrap_user_files, log_sync_error
from superpitch.core import build_retrieval_index, load_model, load_training_data
from superpitch.state import feedback_since_last_train, load_config, save_config, should_auto_retrain
from superpitch.terminal_ui import process_pitch, run_interactive_app
from superpitch.updates import get_update_notice

try:
    from superpitch.sync import fetch_pitches, score_and_save_cloud_pitches
    _SYNC_AVAILABLE = True
except ImportError:
    _SYNC_AVAILABLE = False


def maybe_auto_retrain():
    config = load_config()

    upgrade_retrain = config.get("retrain_after_upgrade", False)

    if not upgrade_retrain and not should_auto_retrain(config):
        return

    if upgrade_retrain:
        print("Merging new base model with your feedback...")
    else:
        pending = feedback_since_last_train(config)
        threshold = int(config.get("auto_retrain_threshold", 20))
        print(f"Auto-retraining on {pending} new feedback labels (threshold {threshold})...")

    try:
        from train import train
        train()
        fresh = load_config()
        fresh.pop("retrain_after_upgrade", None)
        save_config(fresh)
    except Exception as exc:
        print(f"Auto-retrain skipped: {exc}")


def maybe_startup_sync(config, bundle, index_vecs, examples):
    """If signed in, fetch new pitches on startup before the TUI launches."""
    if not _SYNC_AVAILABLE or not config.get("signed_in") or not config.get("session_token"):
        return
    try:
        since = config.get("last_synced_at") or None
        cloud_pitches = fetch_pitches(config["session_token"], since=since)
        if cloud_pitches:
            added = score_and_save_cloud_pitches(cloud_pitches, bundle, index_vecs, examples, config)
            if added:
                print(f"Synced {added} new pitch{'es' if added != 1 else ''}.")
    except PermissionError as exc:
        if "subscription" not in str(exc):
            config.update(signed_in=False, session_token="")
            save_config(config)
    except Exception as exc:
        log_sync_error("startup_sync", exc)


def main():
    created_files = bootstrap_user_files()
    update_notice = get_update_notice()
    maybe_auto_retrain()
    bundle = load_model()
    examples = load_training_data()
    index_vecs = build_retrieval_index(examples) if examples else None
    config = load_config()
    maybe_startup_sync(config, bundle, index_vecs, examples)

    if len(sys.argv) > 1:
        path = sys.argv[1]
        if path == "-":
            text = sys.stdin.read()
        else:
            with open(path, encoding="utf-8", errors="ignore") as f:
                text = f.read()
        process_pitch(bundle, text, index_vecs, examples, source_label=path)
        return

    if update_notice:
        print(
            f"Update available: {update_notice} (current {__version__}). Type /upgrade inside the app."
        )
    run_interactive_app(bundle, index_vecs, examples, created_files)


if __name__ == "__main__":
    main()
