from __future__ import annotations

import asyncio
import json
import os
from dataclasses import asdict

from psycopg import connect
from psycopg.rows import dict_row

from tools.hd2026_ingest_support.constants import (
    INGEST_BATCH,
    PROJECT_CANDIDATES,
    ROOT_DIR,
    SOURCE_CODE,
    build_document_type_rules,
)
from tools.hd2026_ingest_support.discovery import (
    collect_top_level_summary,
    discover_project_documents,
    validate_project_candidates,
)
from tools.hd2026_ingest_support.knowledge_ingest import ingest_qdrant_documents
from tools.hd2026_ingest_support.persistence import (
    ensure_classification_tables,
    replace_entry_rows,
    replace_project_candidates,
    upsert_source,
)

DATABASE_URL = os.getenv(
    "DATABASE_URL",
    "postgresql://dscons_user:dscons_password@127.0.0.1:5432/dscons_operations",
)


async def main() -> None:
    # Giữ entrypoint cũ cho CLI.
    root_dir = ROOT_DIR
    if not root_dir.exists():
        raise SystemExit(f"Directory not found: {root_dir}")

    top_level_rows = collect_top_level_summary(root_dir)
    validate_project_candidates(PROJECT_CANDIDATES)
    rules = build_document_type_rules()
    project_documents_by_project = {
        candidate.project_code: discover_project_documents(candidate, rules)
        for candidate in PROJECT_CANDIDATES
    }

    with connect(DATABASE_URL, autocommit=False, row_factory=dict_row) as connection:
        ensure_classification_tables(connection)
        source_id = upsert_source(connection, root_dir)
        replace_entry_rows(connection, source_id, top_level_rows)
        replace_project_candidates(connection, source_id, PROJECT_CANDIDATES)

    qdrant_summary = await ingest_qdrant_documents(project_documents_by_project)

    print(
        json.dumps(
            {
                "status": "ok",
                "database_url_source": "env"
                if "DATABASE_URL" in os.environ
                else "default",
                "source_code": SOURCE_CODE,
                "source_path": str(root_dir),
                "ingest_batch": INGEST_BATCH,
                "top_level_entries": len(top_level_rows),
                "project_candidates": len(PROJECT_CANDIDATES),
                "classified_owner_dossiers": [
                    row["entry_name"]
                    for row in top_level_rows
                    if row["category"] == "owner_project_dossier"
                ],
                "document_type_rules": [asdict(rule) for rule in rules],
                "qdrant_ingest": qdrant_summary,
            },
            ensure_ascii=False,
            indent=2,
        )
    )


if __name__ == "__main__":
    asyncio.run(main())
