"""Superpitch terminal entrypoint."""

from __future__ import annotations

import sys

from superpitch.app_paths import bootstrap_user_files
from superpitch.core import build_retrieval_index, load_model, load_training_data
from superpitch.state import feedback_since_last_train, load_config, should_auto_retrain
from superpitch.terminal_ui import process_pitch, run_interactive_app


def maybe_auto_retrain():
    config = load_config()
    if not should_auto_retrain(config):
        return

    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()
    except Exception as exc:
        print(f"Auto-retrain skipped: {exc}")


def main():
    created_files = bootstrap_user_files()
    maybe_auto_retrain()
    bundle = load_model()
    examples = load_training_data()
    index_vecs = build_retrieval_index(examples) if examples else None

    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

    run_interactive_app(bundle, index_vecs, examples, created_files)


if __name__ == "__main__":
    main()
