"""Persistencia SQLite para location_agent.

Usa ar_house.db existente del proyecto.
Crea la tabla location_reports si no existe.
"""

from __future__ import annotations

import json
import sqlite3
from pathlib import Path

_PROJECT_ROOT = Path(__file__).resolve().parent.parent
DB_PATH = _PROJECT_ROOT / "ar_house.db"

CREATE_SQL = """
CREATE TABLE IF NOT EXISTS location_reports (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    address TEXT NOT NULL,
    lat REAL,
    lon REAL,
    score_general INTEGER,
    score_crime INTEGER,
    score_property INTEGER,
    score_schools INTEGER,
    score_amenities INTEGER,
    score_demographics INTEGER,
    score_maritime INTEGER,
    score_lifestyle INTEGER,
    raw_data TEXT,
    report_text TEXT,
    pdf_path TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
"""


def _conn() -> sqlite3.Connection:
    conn = sqlite3.connect(DB_PATH)
    conn.row_factory = sqlite3.Row
    return conn


def init_db() -> None:
    """Crea la tabla si no existe."""
    with _conn() as conn:
        conn.execute(CREATE_SQL)
        conn.commit()


def save_report(
    geo: dict,
    scores: dict,
    overall_score: int,
    raw_data: dict,
    report: dict,
) -> int:
    """Guarda el reporte en SQLite. Devuelve el ID insertado."""
    init_db()
    pdf_path = report.get("pdf_path")

    with _conn() as conn:
        cur = conn.execute(
            """
            INSERT INTO location_reports
                (address, lat, lon, score_general,
                 score_crime, score_property, score_schools, score_amenities,
                 score_demographics, score_maritime, score_lifestyle,
                 raw_data, report_text, pdf_path)
            VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)
            """,
            (
                geo.get("address", ""),
                geo.get("lat"),
                geo.get("lon"),
                overall_score,
                scores.get("crime"),
                scores.get("property"),
                scores.get("schools"),
                scores.get("amenities"),
                scores.get("demographics"),
                scores.get("maritime"),
                scores.get("lifestyle"),
                json.dumps(raw_data, ensure_ascii=False),
                report.get("report_text", ""),
                str(pdf_path) if pdf_path else None,
            ),
        )
        conn.commit()
        return cur.lastrowid


def list_reports(limit: int = 50) -> list[dict]:
    """Lista los últimos reportes guardados."""
    init_db()
    with _conn() as conn:
        rows = conn.execute(
            """SELECT id, address, score_general, created_at
               FROM location_reports ORDER BY created_at DESC LIMIT ?""",
            (limit,),
        ).fetchall()
    return [dict(r) for r in rows]


def get_report(report_id: int) -> dict | None:
    """Obtiene un reporte completo por ID."""
    init_db()
    with _conn() as conn:
        row = conn.execute(
            "SELECT * FROM location_reports WHERE id=?", (report_id,)
        ).fetchone()
    if not row:
        return None
    d = dict(row)
    try:
        d["raw_data"] = json.loads(d["raw_data"] or "{}")
    except Exception:
        pass
    return d
