File size: 3,054 Bytes
d0501ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import sys
import os
import json
import shutil
from datetime import datetime, timedelta

# Ensure parent directory is in path
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.routers import analysis, company, health, tenders, documents, oc, tender_details, admin
from app.database import engine, Base, SessionLocal, SQLALCHEMY_DATABASE_URL
from app.models.tender import TenderModel
from app.models.analysis import AnalysisHistoryModel
from app.models.company import CompanyProfileModel
from app.models.oc import OCModel
from app.config import settings

# Copy database to /tmp if needed (Linux/HF Spaces)
if SQLALCHEMY_DATABASE_URL.startswith("sqlite:////tmp/"):
    src_db = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "andesops.db")
    dest_db = "/tmp/andesops.db"
    if os.path.exists(src_db) and not os.path.exists(dest_db):
        print(f"!!! HF DETECTED: Copying initial database from {src_db} to {dest_db} !!!")
        shutil.copy2(src_db, dest_db)

# Create tables
try:
    Base.metadata.create_all(bind=engine)
except Exception as e:
    print(f"!!! Database creation error: {e} !!!")

app = FastAPI(title="AndesOps AI")

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Routes
app.include_router(health.router, prefix="/api", tags=["Health"])
app.include_router(tenders.router, prefix="/api", tags=["Tenders"])
app.include_router(analysis.router, prefix="/api", tags=["Analysis"])
app.include_router(company.router, prefix="/api", tags=["Company"])
app.include_router(documents.router, prefix="/api", tags=["Documents"])
app.include_router(oc.router, prefix="/api", tags=["Purchase Orders"])
app.include_router(tender_details.router, prefix="/api", tags=["Tender Details"])
app.include_router(admin.router, prefix="/api", tags=["Admin"])

@app.on_event("startup")
async def startup_event():
    print("!!! BACKEND STARTING UP !!!")
    db = SessionLocal()
    try:
        print(f"Checking database at: {settings.database_url}")
        count = db.query(TenderModel).count()
        print(f"Current tender count: {count}")
        if count == 0:
            print("Auto-seeding database...")
            # Basic Company Profile - Independent check
            if not db.query(CompanyProfileModel).first():
                print("Seeding Generic Company Profile...")
                db.add(CompanyProfileModel(
                    name="My Company",
                    industry="Consulting",
                    services="General Services",
                    experience="1 year",
                    regions="Nacional",
                    documents_available="None"
                ))
                db.commit()
    except Exception as e:
        print(f"Seed error: {e}")
    finally:
        db.close()

@app.get("/")
def read_root():
    return {"message": "Welcome to AndesOps AI API"}