"""DRHP Drafting Agent - Capital Structure & Shareholding Pattern."""

from __future__ import annotations

import os
from pathlib import Path

from dotenv import load_dotenv

# Load .env file from the same directory as this file
_env_path = Path(__file__).resolve().parent.parent / ".env"
load_dotenv(_env_path)

from syrin import Agent, Budget, FactVerificationGuardrail, Output
from syrin.embedding import Embedding
from syrin.enums import KnowledgeBackend
from syrin.knowledge import (
    ChunkStrategy,
    Knowledge,
)
from syrin.model import Model

from .models import DraftOutput

# Base path for data (relative to this file)
_DATA_DIR = Path(__file__).resolve().parent.parent / "data"


def _data_path(*parts: str) -> Path:
    return _DATA_DIR.joinpath(*parts)


SYSTEM_PROMPT = """You are a DRHP drafting assistant for Capital Structure and Shareholding Pattern.

CRITICAL - Call search_knowledge FIRST. Use these queries: "capital structure", "authorized capital", "issued capital", "shareholding", "PAS-3", "List of Allottees", "allottees", "equity shares", "MOA", "SH-7". Do NOT answer until you have retrieved facts.

RULES:
- Copy numbers and names EXACTLY from search results. Do not invent or approximate.
- Use the company name exactly as it appears in the documents.
- For shareholding: Use the latest shareholding pattern from the documents.
- draft_section MUST be paragraph-style legal disclosure using ONLY facts from search results.
- Do NOT use example company names or invented numbers. Use facts from retrieved documents only.

Output a single valid JSON object (no markdown, no code blocks):
{
  "draft_section": "<paragraph in formal legal language>",
  "sources_used": ["<doc names used>"],
  "auto_extracted_parts": ["<fields extracted from docs>"],
  "requires_review": ["<items needing human verification>"]
}"""


def create_knowledge(data_dir: Path | None = None, api_key: str | None = None) -> Knowledge:
    """Create Knowledge orchestrator with document sources."""
    base = data_dir or _DATA_DIR
    api_key = api_key or os.getenv("OPENAI_API_KEY")
    if not api_key:
        raise ValueError("OPENAI_API_KEY is required for embeddings")

    embedding = Embedding.OpenAI("text-embedding-3-small", api_key=api_key)

    # Load all supported formats from data dir (PAS-3, SH-7, etc.)
    sources = [Knowledge.Directory(str(base), glob="**/*.md")]

    return Knowledge(
        sources=sources,
        embedding=embedding,
        backend=KnowledgeBackend.MEMORY,
        chunk_strategy=ChunkStrategy.RECURSIVE,
        chunk_size=512,
        chunk_min_size=64,
        top_k=12,
        score_threshold=0.2,
        agentic=True,
        agentic_max_iterations=3,
        agentic_decompose=True,
        agentic_grade_results=True,
        agentic_relevance_threshold=0.35,
        agentic_web_fallback=False,
        grounding_enabled=True,
        grounding_extract_facts=True,
        grounding_verify=True,
        grounding_cite_sources=True,
        grounding_confidence=0.7,
        inject_system_prompt=True,
    )


def create_agent(
    *,
    data_dir: Path | None = None,
    api_key: str | None = None,
    model_id: str = "gpt-4o",
) -> Agent:
    """Create the DRHP drafting agent."""
    api_key = api_key or os.getenv("OPENAI_API_KEY")
    knowledge = create_knowledge(data_dir=data_dir, api_key=api_key)

    return Agent(
        name="ipo_drafting_agent",
        description="A DRHP drafting assistant for Capital Structure and Shareholding Pattern.",
        model=Model.OpenAI(model_id, api_key=api_key),
        system_prompt=SYSTEM_PROMPT,
        knowledge=knowledge,
        output=Output(DraftOutput, validation_retries=3),
        max_tool_iterations=15,
        budget=Budget(max_cost=1.0),
        guardrails=[FactVerificationGuardrail()],
        debug=True,
    )
