"""
CLI entry point for convex2pg.

Usage:
    convex2pg <export_dir> [options]
"""

from __future__ import annotations

import argparse
import sys
from pathlib import Path

from .converter import convert_export, TableResult

HEADER = "-- Generated by convex2pg (https://github.com/)\n"


def _build_schema_sql(results: list[TableResult]) -> str:
    parts = [HEADER]
    for r in results:
        parts.append(r.schema_sql + "\n")
    return "\n".join(parts)


def _build_data_sql(results: list[TableResult]) -> str:
    parts = [HEADER]
    for r in results:
        if r.data_sql:
            parts.append(f"-- {r.name} ({r.row_count} rows)")
            parts.append(r.data_sql + "\n")
    return "\n".join(parts)


def main() -> None:
    parser = argparse.ArgumentParser(
        prog="convex2pg",
        description="Convert a Convex snapshot export to PostgreSQL SQL files.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
examples:
  convex2pg ./my-export/
  convex2pg ./my-export/ --output ./sql/
  convex2pg ./my-export/ --schema-only
  convex2pg ./my-export/ --stdout
        """,
    )
    parser.add_argument(
        "export_dir",
        metavar="EXPORT_DIR",
        help="Path to the Convex snapshot export directory",
    )
    parser.add_argument(
        "-o", "--output",
        metavar="DIR",
        help="Directory to write schema.sql and data.sql (default: EXPORT_DIR)",
    )
    parser.add_argument(
        "--schema-only",
        action="store_true",
        help="Only generate schema.sql (no data inserts)",
    )
    parser.add_argument(
        "--data-only",
        action="store_true",
        help="Only generate data.sql (no CREATE TABLE statements)",
    )
    parser.add_argument(
        "--stdout",
        action="store_true",
        help="Print SQL to stdout instead of writing files",
    )
    parser.add_argument(
        "-v", "--verbose",
        action="store_true",
        help="Show per-table details",
    )
    parser.add_argument(
        "--version",
        action="version",
        version="convex2pg 0.1.0",
    )

    args = parser.parse_args()

    export_dir = Path(args.export_dir)
    if not export_dir.is_dir():
        parser.error(f"'{export_dir}' is not a directory")

    results = convert_export(export_dir)
    if not results:
        print("No tables found. Is this a Convex snapshot export directory?", file=sys.stderr)
        sys.exit(1)

    schema_sql = _build_schema_sql(results)
    data_sql   = _build_data_sql(results)

    total_rows = sum(r.row_count for r in results)

    if args.stdout:
        if not args.data_only:
            print(schema_sql)
        if not args.schema_only:
            print(data_sql)
        return

    output_dir = Path(args.output) if args.output else export_dir
    output_dir.mkdir(parents=True, exist_ok=True)

    written: list[str] = []

    if not args.data_only:
        schema_path = output_dir / "schema.sql"
        schema_path.write_text(schema_sql)
        written.append(f"  schema.sql  ({len(results)} tables)")

    if not args.schema_only:
        data_path = output_dir / "data.sql"
        data_path.write_text(data_sql)
        written.append(f"  data.sql    ({total_rows} rows)")

    print(f"✓ Processed {len(results)} tables, {total_rows} total rows")
    for line in written:
        print(line)

    if args.verbose:
        print()
        print("Tables:")
        for r in results:
            print(f"  {r.name:<30} {r.row_count} rows")
