# -*- coding: utf-8 -*-
"""Export cfg_index_parameters table to CSV."""

from __future__ import annotations

import argparse
import csv
import os
import sys
from pathlib import Path
from typing import Any, Dict, List, Optional

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if ROOT not in sys.path:
    sys.path.insert(0, ROOT)

from config.settings import AppConfig
from database.connection import DatabaseConnection
from database.operations import DatabaseOperations

FIELDS = [
    "param_id",
    "index_type",
    "param_name",
    "param_value",
    "description",
    "effective_from",
    "effective_to",
    "created_at",
    "updated_at",
]


def _fetch_rows(db: DatabaseOperations, index_type: Optional[str]) -> List[Dict[str, Any]]:
    base_sql = """
    SELECT
        param_id,
        index_type,
        param_name,
        param_value,
        description,
        effective_from,
        effective_to,
        created_at,
        updated_at
    FROM dws.cfg_index_parameters
    """
    args: List[Any] = []
    if index_type:
        base_sql += " WHERE index_type = %s"
        args.append(index_type)
    base_sql += " ORDER BY index_type, param_name, effective_from, param_id"
    rows = db.query(base_sql, args if args else None)
    return [dict(r) for r in (rows or [])]


def _write_csv(rows: List[Dict[str, Any]], out_csv: Path) -> None:
    out_csv.parent.mkdir(parents=True, exist_ok=True)
    with out_csv.open("w", newline="", encoding="utf-8-sig") as f:
        writer = csv.DictWriter(f, fieldnames=FIELDS)
        writer.writeheader()
        for row in rows:
            writer.writerow({k: row.get(k) for k in FIELDS})


def main() -> None:
    parser = argparse.ArgumentParser(description="Export cfg_index_parameters to CSV.")
    parser.add_argument(
        "--index-type",
        default=None,
        help="Optional index type filter (e.g. RECALL, INTIMACY, NCI, WBI).",
    )
    parser.add_argument(
        "--output-csv",
        default=os.path.join(ROOT, "docs", "cfg_index_parameters.csv"),
        help="Output CSV path.",
    )
    args = parser.parse_args()

    config = AppConfig.load()
    db_conn = DatabaseConnection(config.config["db"]["dsn"])
    db = DatabaseOperations(db_conn)
    try:
        rows = _fetch_rows(db, args.index_type)
        out_csv = Path(args.output_csv)
        _write_csv(rows, out_csv)
        print(f"rows={len(rows)}")
        print(f"csv={out_csv}")
    finally:
        db_conn.close()


if __name__ == "__main__":
    main()
