"""Regenerate threecx/models/_generated.py from swagger.yaml.

Usage:
    uvx --from datamodel-code-generator scripts/generate_models.py

Or run the steps manually:
    rm -rf /tmp/threecx_gen
    uvx --from datamodel-code-generator datamodel-codegen \
        --input swagger.yaml \
        --input-file-type openapi \
        --output /tmp/threecx_gen \
        --output-model-type pydantic_v2.BaseModel \
        --target-python-version 3.10 \
        --snake-case-field \
        --use-double-quotes \
        --use-default \
        --use-schema-description
    python scripts/generate_models.py
"""
from __future__ import annotations

from pathlib import Path

ROOT = Path(__file__).parent.parent
SWAGGER_GEN_DIR = Path("/tmp/threecx_gen")
TARGET = ROOT / "threecx" / "models" / "_generated.py"


def strip_header(text: str) -> str:
    lines = text.splitlines()
    out, in_header = [], True
    for line in lines:
        if in_header and (line.startswith("#") or not line.strip()):
            continue
        in_header = False
        out.append(line)
    return "\n".join(out)


def filter_imports(text: str, drop_prefixes: tuple[str, ...]) -> str:
    return "\n".join(
        line for line in text.splitlines()
        if not any(line.startswith(p) for p in drop_prefixes)
    )


def main() -> None:
    if not (SWAGGER_GEN_DIR / "Pbx" / "__init__.py").exists():
        raise SystemExit(
            f"Run datamodel-codegen first to populate {SWAGGER_GEN_DIR}. See module docstring."
        )

    parent = strip_header((SWAGGER_GEN_DIR / "__init__.py").read_text())
    pbx = strip_header((SWAGGER_GEN_DIR / "Pbx" / "__init__.py").read_text())

    drop = (
        "from __future__",
        "from datetime",
        "from enum",
        "from uuid",
        "from pydantic",
        "from .. import",
    )
    parent = filter_imports(parent, drop).strip()
    pbx = filter_imports(pbx, drop).strip()

    header = '''"""Auto-generated Pydantic models for the 3CX XAPI.

Generated from swagger.yaml using datamodel-code-generator, then post-processed
to use our _Base class (which sets extra='allow' and populate_by_name=True).

Do not edit this file by hand — regenerate via `scripts/generate_models.py`.
"""
from __future__ import annotations

from datetime import time as time_aliased, timedelta
from enum import Enum
from uuid import UUID

from pydantic import AwareDatetime, Field, RootModel, conint, constr

from .base import _Base as BaseModel
'''

    TARGET.write_text(header + "\n\n" + parent + "\n\n\n" + pbx + "\n")
    print(f"Wrote {TARGET} ({len(TARGET.read_text().splitlines())} lines)")


if __name__ == "__main__":
    main()
