"""
taldbt CLI — entry point for `pip install taldbt`

Usage:
    taldbt ui                           # Launch Streamlit web UI
    taldbt discover <talend_dir>        # Scan and analyze a Talend project
    taldbt migrate <talend_dir> <out>   # Full migration to dbt
    taldbt version                      # Print version
"""
import sys
import os


def main():
    args = sys.argv[1:]

    if not args or args[0] in ("-h", "--help", "help"):
        _print_help()
        return

    if args[0] in ("version", "--version", "-v"):
        from taldbt import __version__
        print(f"taldbt v{__version__}")
        return

    if args[0] == "ui":
        _launch_ui()
        return

    if args[0] == "discover" and len(args) >= 2:
        _discover(args[1], args[2] if len(args) > 2 else "migration_plan.json")
        return

    if args[0] == "migrate" and len(args) >= 3:
        _migrate(args[1], args[2])
        return

    print(f"Unknown command: {args[0]}")
    _print_help()
    sys.exit(1)


def _print_help():
    from taldbt import __version__
    print(f"""
taldbt v{__version__} — AI Powered Talend to dbt Migration

Usage:
    taldbt ui                              Launch the web UI
    taldbt discover <talend_dir> [output]  Scan & analyze a Talend project
    taldbt migrate <talend_dir> <out_dir>  Full migration to dbt
    taldbt version                         Print version

Examples:
    taldbt ui
    taldbt discover ./my_talend_project
    taldbt migrate ./my_talend_project ./dbt_output

More info: https://taldbt.netlify.app
    """.strip())


def _launch_ui():
    try:
        import streamlit
    except ImportError:
        print("Streamlit not installed. Run: pip install taldbt[ui]")
        sys.exit(1)

    ui_path = os.path.join(os.path.dirname(__file__), "ui", "app.py")
    os.system(f"streamlit run {ui_path}")


def _discover(input_path, out_path):
    from taldbt.parsers.project_scanner import scan_project
    from taldbt.parsers.xml_parser import parse_job
    from taldbt.models.ast_models import ProjectAST, JobType
    from taldbt.graphing.dag_builder import apply_dag_to_project
    import json

    print(f"[taldbt] Scanning {input_path}...")

    scan = scan_project(input_path)
    project = ProjectAST(
        project_name=os.path.basename(input_path),
        input_path=input_path,
    )

    for entry in scan["process_jobs"]:
        job = parse_job(entry["path"], entry["name"])
        project.jobs[entry["name"]] = job

    for entry in scan.get("joblets", []):
        job = parse_job(entry["path"], entry["name"], JobType.JOBLET)
        project.joblets[entry["name"]] = job

    apply_dag_to_project(project)

    with open(out_path, "w", encoding="utf-8") as f:
        json.dump(project.model_dump(), f, indent=2, default=str)

    n_jobs = len(project.jobs)
    n_src = sum(len(j.sources) for j in project.jobs.values())
    n_comp = sum(len(j.components) for j in project.jobs.values())
    print(f"[taldbt] {n_jobs} jobs, {n_src} sources, {n_comp} components")
    print(f"[taldbt] Discovery complete -> {out_path}")


def _migrate(input_path, output_path):
    from taldbt.parsers.project_scanner import scan_project
    from taldbt.parsers.xml_parser import parse_job
    from taldbt.models.ast_models import ProjectAST
    from taldbt.graphing.dag_builder import apply_dag_to_project
    from taldbt.codegen.model_assembler import assemble_model
    from taldbt.codegen.dbt_scaffolder import scaffold_dbt_project, write_model_file

    print(f"[taldbt] Migrating {input_path} -> {output_path}")

    scan = scan_project(input_path)
    project = ProjectAST(
        project_name=os.path.basename(input_path),
        input_path=input_path,
    )

    for entry in scan["process_jobs"]:
        job = parse_job(entry["path"], entry["name"])
        project.jobs[entry["name"]] = job

    apply_dag_to_project(project)
    scaffold_dbt_project(project, output_path)

    generated = 0
    for name, job in project.jobs.items():
        sql = assemble_model(job)
        if sql:
            write_model_file(sql, name, output_path)
            generated += 1
            print(f"  [ok] {name}")

    print(f"[taldbt] Done. {generated} models generated in {output_path}")


if __name__ == "__main__":
    main()
