from fastapi import APIRouter, Depends, HTTPException, Body
from sqlalchemy.orm import Session
from typing import List, Optional, Dict, Any
from datetime import date
from pydantic import BaseModel, Field

from db.db_connection import get_db
from db.models.house_model import House  # <-- SQLAlchemy model

router = APIRouter(
    prefix="/houses",
    tags=["Houses"]
)

# ===============================
# Pydantic Schemas
# ===============================
class HouseModel(BaseModel):
    title: str = Field(..., example="Luxury Condo in KL")
    price: float = Field(..., example=1200000.00)
    address: str = Field(..., example="Jalan Ampang, Kuala Lumpur")
    property_type: str = Field(..., example="Condominium")
    furnishing_status: str = Field(..., example="Fully Furnished")
    bedroom: int = Field(..., example=3)
    bathroom: int = Field(..., example=2)
    size_sqft: int = Field(..., example=1200)
    broadband_services: Optional[List[str]] = None
    agent: Optional[Dict[str, Any]] = None
    amenities: Optional[List[str]] = None
    facilities: Optional[List[str]] = None
    availability_on: Optional[date] = None
    latitude: Optional[float] = None
    longitude: Optional[float] = None
    images: Optional[List[str]] = None
    crime_level: Optional[str] = Field(None, example="Low, High")  

    class Config:
        from_attributes = True


class HouseResponse(HouseModel):
    id: int

    class Config:
        from_attributes = True


# Example JSON (used in Body for Swagger docs)
house_example = {
    "title": "Modern Semi-D in Shah Alam",
    "price": 850000,
    "address": "Shah Alam, Selangor",
    "property_type": "Landed House",
    "furnishing_status": "Partially Furnished",
    "bedroom": 4,
    "bathroom": 3,
    "size_sqft": 2000,
    "broadband_services": ["TIME", "Unifi"],
    "agent": {"name": "Alice Tan", "contact": "+60 19-9876543"},
    "amenities": ["Playground", "BBQ Area"],
    "facilities": ["CCTV", "Covered Parking"],
    "availability_on": "2025-10-01",
    "latitude": 3.0738,
    "longitude": 101.5183,
    "images": [
        "uploads/semiD_livingroom.jpg",
        "uploads/semiD_kitchen.jpg"
    ],
    "crime_level": "Low" 
}


# ===============================
# Routes
# ===============================

@router.post("/", response_model=HouseResponse)
def add_house(
    house_data: HouseModel = Body(..., example=house_example),
    db: Session = Depends(get_db)
):
    try:
        new_house = House(**house_data.model_dump())
        db.add(new_house)
        db.commit()
        db.refresh(new_house)
        return new_house
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"Error creating house: {str(e)}")


@router.get("/", response_model=List[HouseResponse])
def list_houses(db: Session = Depends(get_db)):
    try:
        houses = db.query(House).order_by(House.id.desc()).all()
        return houses
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error getting houses: {str(e)}")


@router.get("/{house_id}", response_model=HouseResponse)
def get_house(house_id: int, db: Session = Depends(get_db)):
    try:
        house = db.query(House).filter_by(id=house_id).first()
        if not house:
            raise HTTPException(status_code=404, detail="House not found")
        return house
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error getting house: {str(e)}")


@router.put("/{house_id}/edit", response_model=HouseResponse)
def update_house(
    house_id: int,
    house_data: HouseModel = Body(..., example=house_example),
    db: Session = Depends(get_db)
):
    try:
        house = db.query(House).filter_by(id=house_id).first()
        if house:
            for key, value in house_data.model_dump().items():
                setattr(house, key, value)
            db.commit()
            db.refresh(house)
            return house
        else:
            raise HTTPException(status_code=404, detail="House not found")
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"Error updating house: {str(e)}")


@router.delete("/{house_id}/delete")
def delete_house(house_id: int, db: Session = Depends(get_db)):
    try:
        house = db.query(House).filter_by(id=house_id).first()
        if house:
            db.delete(house)
            db.commit()
            return {"result": "ok"}
        else:
            raise HTTPException(status_code=404, detail="House not found")
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"Error deleting house: {str(e)}")


@router.post("/bulk", response_model=List[HouseResponse], status_code=201)
def create_multiple_houses(
    houses: List[HouseModel] = Body(..., example=[house_example]),
    db: Session = Depends(get_db)
):
    """
    Create multiple house records at once.
    """
    try:
        new_houses_db = [House(**house.model_dump()) for house in houses]
        db.add_all(new_houses_db)
        db.commit()
        for house in new_houses_db:
            db.refresh(house)
        return new_houses_db
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"Error creating houses: {str(e)}")
