"""
Validate a schema-contract change before you restart the API with it.

This is the tool to run every time you edit `app/schema/oremus.sql`
(or point `SCHEMA_SOURCE_PATH` at a new dump) and/or
`schema_customizations.json`. It exercises *exactly* the same pipeline the
app runs at startup - DDL parsing, foreign-key/relationship graph building,
and the customization overlay - without needing Ollama, Redis, or a
reachable MySQL connection. If this script passes, the app will start
cleanly with the new schema; if it fails, you get a precise, actionable
error instead of a crash at request time or a confusing startup traceback.

Usage:
    python scripts/validate_schema.py
    python scripts/validate_schema.py --schema path/to/other_dump.sql
    python scripts/validate_schema.py --customizations path/to/other.json
    python scripts/validate_schema.py --quiet   # only print on failure (CI use)

Exit code 0 = safe to deploy. Exit code 1 = fix the reported issue first.
"""
from __future__ import annotations

import argparse
import sys
from pathlib import Path

# Allow running as `python scripts/validate_schema.py` from the repo root
# without having installed the package.
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from app.core.config import get_settings  # noqa: E402
from app.core.exceptions import AppError  # noqa: E402
from app.schema.loader import load_schema_contract  # noqa: E402
from app.schema.registry import build_snapshot  # noqa: E402
from app.schema.relationship_mapper import build_relationship_graph  # noqa: E402


def _parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument(
        "--schema",
        default=None,
        help="Path to the SQL schema contract to validate. Defaults to SCHEMA_SOURCE_PATH from .env/settings.",
    )
    parser.add_argument(
        "--customizations",
        default=None,
        help="Path to the schema customizations JSON overlay. Defaults to SCHEMA_CUSTOMIZATIONS_PATH from .env/settings.",
    )
    parser.add_argument(
        "--quiet",
        action="store_true",
        help="Only print output when validation fails. Useful in pre-deploy CI steps.",
    )
    return parser.parse_args()


def main() -> int:
    args = _parse_args()
    settings = get_settings()
    schema_path = args.schema or settings.schema_source_path
    customizations_path = args.customizations or settings.schema_customizations_path

    def log(message: str = "") -> None:
        if not args.quiet:
            print(message)

    log(f"Schema contract:  {schema_path}")
    log(f"Customizations:   {customizations_path}")
    log()

    # Step 1: parse the raw DDL. Catches malformed CREATE TABLE/ALTER TABLE
    # statements, missing files, and unreadable files.
    try:
        raw_tables = load_schema_contract(schema_path)
    except AppError as exc:
        print(f"FAILED while parsing the schema contract:\n  {exc.message}", file=sys.stderr)
        return 1

    # Step 2: build the FK relationship graph. This never raises - a foreign
    # key pointing at a table outside the dump is silently dropped from the
    # graph (see relationship_mapper), so surface that here as a warning
    # instead of leaving it invisible. It usually means the dump is a
    # partial export that's missing a referenced table.
    relationships = build_relationship_graph(raw_tables)
    dangling_fks: list[str] = []
    for table_name, table in raw_tables.items():
        for fk in table.foreign_keys:
            if fk.referred_table not in raw_tables:
                dangling_fks.append(f"{table_name}.{','.join(fk.constrained_columns)} -> {fk.referred_table} (missing)")

    tables_without_pk = sorted(name for name, table in raw_tables.items() if not table.primary_keys)

    # Step 3: build the descriptor snapshot and apply the customization
    # overlay - the exact validated pipeline used at startup. Rejects
    # unknown tables/columns, duplicate/ambiguous aliases, and malformed
    # entries.
    try:
        snapshot = build_snapshot(schema_path, customizations_path)
    except AppError as exc:
        print(f"FAILED while applying schema customizations:\n  {exc.message}", file=sys.stderr)
        return 1

    log(f"OK  - {len(raw_tables)} table(s) parsed from the schema contract")
    log(f"OK  - {len(relationships)} foreign-key relationship(s) built")
    log(f"OK  - {len(snapshot.tables)} table(s) visible to the app after customizations")
    log()

    for name in sorted(snapshot.tables):
        table = snapshot.tables[name]
        aliases = f" (aliases: {', '.join(table.aliases)})" if table.aliases else ""
        log(f"  - {name}: {len(table.columns)} column(s){aliases}")

    if tables_without_pk:
        log()
        log("WARNING: table(s) with no primary key detected (joins/record-position")
        log("ordering may be less reliable for these):")
        for name in tables_without_pk:
            log(f"  - {name}")

    if dangling_fks:
        log()
        log("WARNING: foreign key(s) reference a table not present in this schema")
        log("contract. This usually means the dump is a partial export. These")
        log("relationships are silently excluded from joins:")
        for entry in dangling_fks:
            log(f"  - {entry}")

    log()
    log("Schema contract and customizations are valid. Safe to restart the API.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
