import asyncio
import json
import csv
import io
import os
from typing import List, Optional
from contextlib import asynccontextmanager

from fastapi import FastAPI, Request, Query, HTTPException, Response
from fastapi.responses import HTMLResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel
from dotenv import load_dotenv

load_dotenv()

from services.database import (
    init_db,
    add_to_watchlist,
    get_watchlist,
    remove_from_watchlist
)
from services.generator import generate_candidates, sanitize_keyword
from services.checker import verify_domain_full_pipeline
from services.pricing import TLD_STANDARD_PRICING

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Initialize SQLite database on startup
    await init_db()
    yield

app = FastAPI(
    title="DomainPulse - Special Domain Discovery",
    description="Official DNS, RDAP & WHOIS Engine for High-Value, Standard-Rate Domains",
    version="1.0.0",
    lifespan=lifespan
)

# Static and Templates
os.makedirs("static/css", exist_ok=True)
os.makedirs("static/js", exist_ok=True)
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")

class WatchlistRequest(BaseModel):
    domain: str
    tld: Optional[str] = ""
    price_reg: Optional[float] = 0.0
    price_ren: Optional[float] = 0.0
    score: Optional[int] = 0
    is_hack: Optional[bool] = False
    notes: Optional[str] = ""

@app.get("/", response_class=HTMLResponse)
async def serve_index(request: Request):
    """Render the modern Linear-styled SaaS dashboard."""
    return templates.TemplateResponse(
        request=request,
        name="index.html",
        context={"tld_pricing": TLD_STANDARD_PRICING}
    )

@app.get("/api/stream-search")
async def stream_domain_search(
    keyword: Optional[str] = Query("", description="Keyword or seed topic"),
    pattern: str = Query("all", description="Pattern: brandables, combos, hacks, prefix_suffix, all"),
    tlds: str = Query("com,net,org,co,app,dev,xyz,ai,io,si,me,so,sh,gg,to,ly,is,us,uk,de,ch,it,in,es,nl"),
    trademark_filter: bool = Query(True, description="Exclude trademark matches and typosquatting"),
    standard_rate_only: bool = Query(True, description="Exclude registry-premium markups"),
    max_price: Optional[float] = Query(None, description="Maximum annual registration price"),
    budget_friendly: bool = Query(False, description="Filter for budget friendly (<$15) TLDs"),
    limit: int = Query(60, description="Max candidates to evaluate")
):
    """
    Server-Sent Events (SSE) streaming endpoint:
    Streams available standard-rate domains, live verification progress,
    and filtered statistics to the frontend in real time.
    """
    selected_tlds = [t.strip().lstrip(".").lower() for t in tlds.split(",") if t.strip()]
    if not selected_tlds:
        selected_tlds = ["com", "io", "ai", "co", "app", "dev"]

    if budget_friendly:
        selected_tlds = [
            t for t in selected_tlds
            if t in TLD_STANDARD_PRICING and TLD_STANDARD_PRICING[t].get("budget", False)
        ]
        if not selected_tlds:
            selected_tlds = ["com", "net", "org", "app", "dev", "xyz", "de", "uk", "us", "si", "me"]

    # Generate candidate domains
    candidates = generate_candidates(
        keyword=keyword or "",
        pattern=pattern,
        selected_tlds=selected_tlds,
        max_candidates=min(limit, 150)
    )

    async def event_generator():
        total = len(candidates)
        # 1. Initial configuration event
        yield f"event: init\ndata: {json.dumps({'total': total, 'selected_tlds': selected_tlds})}\n\n"

        checked_count = 0
        found_count = 0
        tm_filtered_count = 0
        premium_filtered_count = 0

        # Concurrency worker pool using asyncio.Queue
        queue = asyncio.Queue()
        for c in candidates:
            await queue.put(c)

        concurrency = 8  # Balanced to avoid IANA socket rate-limiting

        async def worker():
            nonlocal checked_count, found_count, tm_filtered_count, premium_filtered_count
            results = []
            while not queue.empty():
                try:
                    candidate = queue.get_nowait()
                except asyncio.QueueEmpty:
                    break

                try:
                    result = await verify_domain_full_pipeline(
                        candidate=candidate,
                        trademark_safe_filter=trademark_filter,
                        standard_rate_only=standard_rate_only,
                        max_price=max_price,
                        keyword=keyword
                    )
                except Exception:
                    result = None

                queue.task_done()
                results.append(result)
            return results

        # Process in batches to stream smoothly
        batch_size = 6
        for i in range(0, total, batch_size):
            batch = candidates[i:i + batch_size]
            tasks = [
                verify_domain_full_pipeline(
                    candidate=c,
                    trademark_safe_filter=trademark_filter,
                    standard_rate_only=standard_rate_only,
                    max_price=max_price,
                    keyword=keyword
                )
                for c in batch
            ]
            batch_results = await asyncio.gather(*tasks, return_exceptions=True)

            for res in batch_results:
                checked_count += 1
                if isinstance(res, dict):
                    filtered = res.get("filtered")
                    if filtered == "trademark_conflict":
                        tm_filtered_count += 1
                    elif filtered == "registry_premium":
                        premium_filtered_count += 1
                    elif res.get("is_available"):
                        found_count += 1
                        # Stream found available domain
                        yield f"event: domain\ndata: {json.dumps(res)}\n\n"

                # Stream progress heartbeat
                progress_data = {
                    "checked": checked_count,
                    "total": total,
                    "found": found_count,
                    "tm_filtered": tm_filtered_count,
                    "premium_filtered": premium_filtered_count
                }
                yield f"event: progress\ndata: {json.dumps(progress_data)}\n\n"
                # Brief yield to flush buffer cleanly
                await asyncio.sleep(0.02)

        # Final complete event
        final_summary = {
            "checked": checked_count,
            "total": total,
            "found": found_count,
            "tm_filtered": tm_filtered_count,
            "premium_filtered": premium_filtered_count,
            "status": "complete"
        }
        yield f"event: complete\ndata: {json.dumps(final_summary)}\n\n"

    return StreamingResponse(
        event_generator(),
        media_type="text/event-stream",
        headers={
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "X-Accel-Buffering": "no"
        }
    )

# Watchlist Endpoints
@app.get("/api/watchlist")
async def fetch_watchlist():
    """Retrieve saved domains in user's watchlist."""
    items = await get_watchlist()
    return {"watchlist": items, "count": len(items)}

@app.post("/api/watchlist")
async def save_watchlist(req: WatchlistRequest):
    """Add a domain to the local watchlist."""
    success = await add_to_watchlist(req.dict())
    if not success:
        raise HTTPException(status_code=400, detail="Could not save domain to watchlist")
    return {"status": "success", "domain": req.domain}

@app.delete("/api/watchlist/{domain}")
async def delete_from_watchlist(domain: str):
    """Remove a domain from watchlist."""
    await remove_from_watchlist(domain)
    return {"status": "success", "domain": domain}

@app.get("/api/export-csv")
async def export_csv(source: str = Query("watchlist")):
    """Export watchlist or domains as downloadable CSV."""
    output = io.StringIO()
    writer = csv.writer(output)
    writer.writerow([
        "Domain", "TLD", "Registration Price (USD)", "Renewal Price (USD)",
        "Special Score", "Domain Hack", "Notes", "Discovered Date"
    ])

    if source == "watchlist":
        items = await get_watchlist()
        for item in items:
            writer.writerow([
                item["domain"],
                item["tld"],
                f"${item['price_reg']:.2f}" if item.get("price_reg") else "N/A",
                f"${item['price_ren']:.2f}" if item.get("price_ren") else "N/A",
                item["score"],
                "Yes" if item.get("is_hack") else "No",
                item.get("notes", ""),
                item.get("created_at", "")
            ])

    output.seek(0)
    return Response(
        content=output.getvalue(),
        media_type="text/csv",
        headers={"Content-Disposition": f"attachment; filename=domains_{source}.csv"}
    )

@app.get("/api/tlds")
async def list_supported_tlds():
    """List all supported TLDs and their baseline rates."""
    return {"tlds": TLD_STANDARD_PRICING}

if __name__ == "__main__":
    import uvicorn
    host = os.getenv("HOST", "127.0.0.1")
    port = int(os.getenv("PORT", 8000))
    uvicorn.run("app:app", host=host, port=port, reload=True)
