"""Register agent outputs as project assets (shared DB helpers)."""
from __future__ import annotations

import json
from typing import Any, Optional

from app.db import execute, fetch_one


def get_or_create_agent_project(agent_key: str, client_id: int | None = None) -> int:
    key = (agent_key or "agent").strip().lower()
    row = fetch_one(
        """
        SELECT id FROM cockpit_projects
        WHERE metadata->>'auto_agent' = %s AND status = 'active'
        ORDER BY updated_at DESC LIMIT 1
        """,
        (key,),
    )
    if row:
        return int(row["id"])
    title = f"Agent · {key}"
    created = fetch_one(
        """
        INSERT INTO cockpit_projects (name, client_id, description, created_by, metadata, updated_at)
        VALUES (%s, %s, %s, %s, %s::jsonb, NOW())
        RETURNING id
        """,
        (
            title,
            client_id,
            f"Automatisch project voor {key} output",
            key,
            json.dumps({"auto_agent": key}),
        ),
    )
    return int(created["id"])


def register_agent_output(
    asset_type: str,
    title: str,
    ref_id: str | None = None,
    payload: dict | None = None,
    project_id: int | None = None,
    source_agent: str | None = None,
    created_by: str | None = None,
    file_path: str | None = None,
) -> dict[str, Any] | None:
    agent = (source_agent or created_by or "agent").strip().lower()
    pid = project_id or get_or_create_agent_project(agent)

    if ref_id:
        existing = fetch_one(
            """
            SELECT id FROM project_assets
            WHERE project_id = %s AND asset_type = %s AND ref_id = %s
            LIMIT 1
            """,
            (pid, asset_type, ref_id),
        )
        if existing:
            return {"id": existing["id"], "project_id": pid, "dedup": True}

    row = fetch_one(
        """
        INSERT INTO project_assets (project_id, asset_type, ref_id, title, file_path, payload, created_by, source_agent)
        VALUES (%s, %s, %s, %s, %s, %s::jsonb, %s, %s)
        RETURNING id, project_id, asset_type, ref_id, title
        """,
        (
            pid,
            asset_type,
            ref_id,
            title[:255],
            file_path,
            json.dumps(payload or {}),
            created_by or agent,
            agent,
        ),
    )
    execute("UPDATE cockpit_projects SET updated_at = NOW() WHERE id = %s", (pid,))
    return dict(row) if row else None
